Last active
August 29, 2015 14:16
-
-
Save joebuckle-dev/b4dddc867506bf40b46b to your computer and use it in GitHub Desktop.
Example of sorting numbers in a weight-based order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var items = function(num) { | |
var arr = [1,3,3,5,2,7,4,10,6,4]; | |
/* | |
* Sort array low-high first | |
*/ | |
arr.sort(function(a,b) { | |
return a - b; | |
}); | |
/* | |
* Sort array matter of known integer | |
*/ | |
return sort_items(num, arr); | |
} | |
var sort_items = function(num, arr) { | |
/* New output array */ | |
var out = [], | |
/* sorted is false by default */ | |
sorted = false, | |
sorting = function(arr) { | |
/* | |
* Set cursor to 0 | |
*/ | |
var curr = arr[0], | |
/* | |
* Get absolute number in array | |
*/ | |
diff = Math.abs (num - curr); | |
/* | |
* Loop through the array and find the | |
* closest match | |
*/ | |
for (var i = 0; i < arr.length; i++) { | |
var newdiff = Math.abs (num - arr[i]); | |
if (newdiff < diff) { | |
diff = newdiff; | |
curr = arr[i]; | |
} | |
} | |
/* | |
* Push cursor value to output array | |
*/ | |
out.push(curr); | |
/* | |
* Get the index of cursor selected | |
* value in array and remove | |
*/ | |
var index = arr.indexOf(curr); | |
if (index > -1) { | |
arr.splice(index, 1); | |
} | |
/* | |
* If there is still length in the | |
* array, repeat... | |
*/ | |
if(arr.length>0) { | |
sorting(arr); | |
} else { | |
sorted = true; | |
} | |
/* | |
* Return new sorted array | |
*/ | |
if(sorted==true) { | |
return out; | |
} | |
} | |
return sorting(arr); | |
} | |
// num = 1 | |
[1, 2, 3, 3, 4, 4, 5, 6, 7, 10] | |
// num = 2 | |
[2, 1, 3, 3, 4, 4, 5, 6, 7, 10] | |
// num = 3 | |
[3, 3, 2, 4, 4, 1, 5, 6, 7, 10] | |
// num = 4 | |
[4, 4, 3, 3, 5, 2, 6, 1, 7, 10] | |
// num = 5 | |
[5, 4, 4, 6, 3, 3, 7, 2, 1, 10] | |
// num = 6 | |
[6, 5, 7, 4, 4, 3, 3, 2, 10, 1] | |
// num = 7 | |
[7, 6, 5, 4, 4, 10, 3, 3, 2, 1] | |
// num = 8 | |
[7, 6, 10, 5, 4, 4, 3, 3, 2, 1] | |
// num = 9 | |
[10, 7, 6, 5, 4, 4, 3, 3, 2, 1] | |
// num = 10 | |
[10, 7, 6, 5, 4, 4, 3, 3, 2, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment