I have a array like this:
const arr = [['Dog', 'Cat', 'Fish', 'Bird'],[1, 4, 2, 3]];
How would I sort it so its in the order:
const arr = [['Dog', 'Fish', 'Bird', 'Cat'],[1, 2, 3, 4]];
I have a array like this:
const arr = [['Dog', 'Cat', 'Fish', 'Bird'],[1, 4, 2, 3]];
How would I sort it so its in the order:
const arr = [['Dog', 'Fish', 'Bird', 'Cat'],[1, 2, 3, 4]];
zip them, sort, and zip again:
let zip = args => args[0].map((_, i) => args.map(a => a[i]))
//
const arr = [['Dog', 'Cat', 'Fish', 'Bird'],[1, 4, 2, 3]];
r = zip(zip(arr).sort((x, y) => x[1] - y[1]))
console.log(r)
Array#reduce, iterate over items while updating a Map where the key is the item and the value is its initial indexArray#sort and Map#get, sort the items according to the index map aboveArray#sort, sort the indices arrayconst sort = ([ items, indices ]) => {
const indexMap = items.reduce((map, item, index) =>
map.set(item, indices[index])
, new Map);
return [
items.sort((a, b) => indexMap.get(a) - indexMap.get(b)),
indices.sort()
];
}
console.log( sort([['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]]) );
You could sort an array of indices amnd map the values according to the indices array.
const
array = [['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]],
indices = [...array[1].keys()].sort((a, b) => array[1][a] - array[1][b]);
for (let i = 0; i < array.length; i++)
array[i] = indices.map(j => array[i][j]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }