-
-
Save leeoniya/a4bc7187250550e638059690bd3e9087 to your computer and use it in GitHub Desktop.
Sorting multiple arrays in Javascript
This file contains 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
/** | |
* Sorts all arrays together with the first. Pass either a list of arrays, or a map. Any key is accepted. | |
* Array|Object arrays [sortableArray, ...otherArrays]; {sortableArray: [], secondaryArray: [], ...} | |
* Function comparator(?,?) -> int optional compareFunction, compatible with Array.sort(compareFunction) | |
*/ | |
function sortArrays(arrays, comparator = (a, b) => (a < b) ? -1 : (a > b) ? 1 : 0) { | |
let arrayKeys = Object.keys(arrays); | |
let sortableArray = Object.values(arrays)[0]; | |
let indexes = Object.keys(sortableArray); | |
let sortedIndexes = indexes.sort((a, b) => comparator(sortableArray[a], sortableArray[b])); | |
let sortByIndexes = (array, sortedIndexes) => sortedIndexes.map(sortedIndex => array[sortedIndex]); | |
if (Array.isArray(arrays)) { | |
return arrayKeys.map(arrayIndex => sortByIndexes(arrays[arrayIndex], sortedIndexes)); | |
} else { | |
let sortedArrays = {}; | |
arrayKeys.forEach((arrayKey) => { | |
sortedArrays[arrayKey] = sortByIndexes(arrays[arrayKey], sortedIndexes); | |
}); | |
return sortedArrays; | |
} | |
} |
This file contains 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
let people = ["john", "benny", "sally", "george"]; | |
let peopleIds = [10, 20, 30, 40]; | |
sortArrays([people, peopleIds]); | |
[["benny", "george", "john", "sally"], [20, 40, 10, 30]] // output | |
sortArrays({people, peopleIds}); | |
{"people": ["benny", "george", "john", "sally"], "peopleIds": [20, 40, 10, 30]} // output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment