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]];
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]]) );
Be sure that your index array has all numbers from 1 to n:
function deepSort(arr2d) {
const [stringArr, indexArr] = arr2d
const result = []
indexArr.forEach((index, i) => result[index - 1] = stringArr[i])
return [result, indexArr.sort()]
}
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; }