Skip to content

Instantly share code, notes, and snippets.

@kimhogeling
Last active August 29, 2015 14:23
Show Gist options
  • Save kimhogeling/1c1c42d3f9a7ba723e9a to your computer and use it in GitHub Desktop.
Save kimhogeling/1c1c42d3f9a7ba723e9a to your computer and use it in GitHub Desktop.
sort an array containing arrays with help of a given key

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]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment