简体   繁体   English

在 JS 中对二维数组进行排序

[英]Sort 2D Array in JS

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: zip他们,排序,然后再次zip

 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)

  • Using Array#reduce , iterate over items while updating a Map where the key is the item and the value is its initial index使用Array#reduce迭代items ,同时更新Map ,其中键是项目,值是其初始索引
  • Using Array#sort and Map#get , sort the items according to the index map above使用Array#sortMap#get ,根据上面的索引 map 对项目进行排序
  • Using Array#sort , sort the indices array使用Array#sort对索引数组进行排序

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

Be sure that your index array has all numbers from 1 to n:确保您的索引数组包含从 1 到 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.您可以根据索引数组对索引数组和 map 值进行排序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM