0

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]];
1
  • 2
    Please add the code you've attempted to your question as a minimal reproducible example. Commented Nov 21, 2022 at 16:13

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0
  • Using Array#reduce, iterate over items while updating a Map where the key is the item and the value is its initial index
  • Using Array#sort and Map#get, sort the items according to the index map above
  • Using Array#sort, sort the indices array

const 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]]) );

Comments

0

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()]
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.