Created
October 5, 2017 19:55
-
-
Save sean-codes/2f50ec02a6c1d4fd7066b39d3d39bbcd to your computer and use it in GitHub Desktop.
JavaScript Array Sort
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
function sortArr(arr, func){ | |
var sortedArr = [] | |
for(var i in arr){ | |
for(var o in sortedArr){ | |
if(func ? func(arr[i], sortedArr[o]) < 0 : arr[i] < sortedArr[o]){ break } | |
o++ | |
} | |
sortedArr.splice(o, 0, arr[i]) | |
} | |
return sortedArr | |
} | |
var arrNumbers = [999, 3, 6, 1, 3, 565, 3, 2, 11, 1] | |
var arrLetters = ['a', 'b', 'z', 'd', 'b', 'y', 'cats'] | |
// Sort High to Low | |
console.log('Low -> High', sortArr(arrNumbers, function(a, b){ return a - b })) | |
// Sort Low to High | |
console.log('High -> Low', sortArr(arrNumbers, function(a, b){ return b - a })) | |
// Sort Letters | |
console.log('Alphabetically', sortArr(arrLetters)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment