javascript - 基于多个标准对多维数组进行排序

标签 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);

最佳答案

首先将给定的数组转换为集合。然后使用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))

关于javascript - 基于多个标准对多维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474453/

相关文章:

javascript - 无法在循环内添加 Google 标记

arrays - 获取数组 bash 的随机元素的函数

java - 将所有逻辑表达式变量放入数组中

algorithm - 使用附加数据结构的线性排序(查找集合中值的时间复杂度为 O(1),添加元素的时间复杂度为 O(1))

javascript - 在 Node.js 中处理回滚的 MySQL 事务

javascript - MongoDB 获取最后一个元素不能与 node.js 一起正常工作

javascript - 在 AngularJS 的 ng-grid 单元格中检测 Ctrl+Alt+O 按键

javascript - 将 keydown 事件从父窗口转发到包含 Reveal.js 的 iframe

java - 带有排序的 Spring JPA 规范

memory - 用有限的内存排序