基于多个条件对多维数组进行排序

时间:2019-10-20 15:25:42

标签: javascript arrays sorting

我正在尝试找出一种有效的方法来根据另一个数组的多少个值对多维数组进行排序。

给出以下数组: [1,2,3,4,5,6,7,8,9,10]

我正在尝试根据所包含的这些值的数量对另一个数组进行排序。

[
  [1,3,5,7,9,22],
  [1,200,300,400,500,600],
  [1,2,3,4,5,6]
]

因此,我尝试获取的代码将返回:

[
  [1,2,3,4,5,6],
  [1,3,5,7,9,22],
  [1,200,300,400,500,600]
]

我认为我的工作效率很低,可以用我不知道的方法更好或更简洁地编写?

https://jsfiddle.net/gb3fsLdv/

const compareNums = [1,2,3,4,5,6,7,8,9,10];
let ourData = [
  [1,2,3,100,200,300],
  [100,200,300,400,500,600],
  [1,2,3,5,6,9]
];

function sortArr(compare, data){
  let indexMatches = [];
  data.map(arr => {
    let count = 0;
    compare.map(num => {
      if(arr.includes(num)){ 
        count++ 
        }
    })
    indexMatches.push(count);
  })
  // So now I have indexMatches with a count of how many hits each array has in the correct index order as the original data
  // And I can use data to sort them based on these values...
  // Little stuck how to relate the two so the same sorting happens to both arrays
}

sortArr(compareNums, ourData);

1 个答案:

答案 0 :(得分:3)

首先将给定数组转换为set。然后使用filter()获取其他数组中包含的元素数

const data = [
  [1,3,5,7,9,22],
  [1,200,300,400,500,600],
  [1,2,3,4,5,6]
]

let arr = [1,2,3,4,5,6,7,8,9,10];

function getCount(arr, set){
  return arr.filter(x => set.has(x)).length
}
function sortOnCount(data, arr){
  let set = new Set(arr);
  return data.slice(0).sort((a, b) => getCount(b, set) - getCount(a, set))
}

console.log(sortOnCount(data, arr))