Home > database >  Sort 2D Array in JS
Sort 2D Array in JS

Time:11-22

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related