This function can be used to sort arrays which contain arrays. It does this with help of a given key. This key represents which of the inner arrays item should be used for the sorting.
/**
* Sort an array which is filled with arrays.
* The given key of the array items indicates how to sort.
* 0 stands for the first item of each array, 1 stands for the second item of each array, etc.
* @param Number arrKey The key of the array items which indicate how to sort.
* @param Boolean ascOrDesc True if needs to sort descending instead of normal ascending.
*/
function sortArrayContainingArraysByKey(arrKey, ascOrDesc) {
var result;
// -1 is used in the comparison to achieve descending.
ascOrDesc = ascOrDesc ? '-1' : '1';
// The actual comparing.
return function (a, b) {
result = (a[arrKey] < b[arrKey]) ? -1 : (a[arrKey] > b[arrKey]) ? 1 : 0;
return result * ascOrDesc;
}
}
It can be used like this:
[
['the', 4],
['jam', 5],
['up', 9],
['it', 7],
['pump', 6],
['up', 2],
['pump', 1]
].sort(sortArrayContainingArraysByKey(1));
/**
Output:
[
['pump', 1],
['up', 2],
['the', 4],
['jam', 5],
['pump', 6],
['it', 7],
['up', 9]
]
*/