Sort two arrays the same way

Viewed 55919

For example, if I have these arrays:

var name = ["Bob","Tom","Larry"];
var age =  ["10", "20", "30"];

And I use name.sort() the order of the "name" array becomes:

var name = ["Bob","Larry","Tom"];

But, how can I sort the "name" array and have the "age" array keep the same order? Like this:

var name = ["Bob","Larry","Tom"];
var age =  ["10", "30", "20"];
12 Answers

You could get the indices of name array using Array.from(name.keys()) or [...name.keys()]. Sort the indices based on their value. Then use map to get the value for the corresponding indices in any number of related arrays

const indices = Array.from(name.keys())
indices.sort( (a,b) => name[a].localeCompare(name[b]) )

const sortedName = indices.map(i => name[i]),
const sortedAge = indices.map(i => age[i])

Here's a snippet:

const name = ["Bob","Tom","Larry"],
      age =  ["10", "20", "30"],
      
      indices = Array.from(name.keys())
                     .sort( (a,b) => name[a].localeCompare(name[b]) ),
                     
      sortedName = indices.map(i => name[i]),
      sortedAge = indices.map(i => age[i])

console.log(indices)
console.log(sortedName)
console.log(sortedAge)

This solution (my work) sorts multiple arrays, without transforming the data to an intermediary structure, and works on large arrays efficiently. It allows passing arrays as a list, or object, and supports a custom compareFunction.

Usage:

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

Algorithm:

  • Create a list of indexes of the main array (sortableArray)
  • Sort the indexes with a custom compareFunction that compares the values, looked up with the index
  • For each input array, map each index, in order, to its value

Implementation:

/**
 *  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;
    }
}

See also https://gist.github.com/boukeversteegh/3219ffb912ac6ef7282b1f5ce7a379ad

If performance matters, there is sort-ids package for that purpose:

var sortIds = require('sort-ids')
var reorder = require('array-rearrange')

var name = ["Bob","Larry","Tom"];
var age =  [30, 20, 10];

var ids = sortIds(age)
reorder(age, ids)
reorder(name, ids)

That is ~5 times faster than the comparator function.

How about:

var names = ["Bob","Tom","Larry"];
var ages =  ["10", "20", "30"];
var n = names.slice(0).sort()
var a = [];
for (x in n)
{
i = names.indexOf(n[x]);
a.push(ages[i]);
names[i] = null;
}
names = n
ages = a
Related