首页 > 解决方案 > 按给定的数字序列对 Javascript 数组进行排序

问题描述

我有一个 Javascript 对象数组。它们中的每一个都有一个type介于 1 和 4 之间的整数属性。根据客户端的不同,我想按此type属性的单个数字序列对数组成员进行排序。我的想法是定义一个具有所需序列的数组,例如const desiredOrder = [4, 2, 3, 1];. 然后我的脚本应该按此列表对对象数组进行排序,同时保持整体顺序。例如:

var list = [
  {id: 1, type: 2},
  {id: 2, type: 4},
  {id: 3, type: 2},
  {id: 4, type: 1},
  {id: 5, type: 2},
  {id; 6, type: 3}
];

var orderedList = [
  {id: 2, type: 4},
  {id: 1, type: 2},
  {id: 3, type: 2},
  {id: 5, type: 2},
  {id; 6, type: 3},
  {id: 4, type: 1}
];

在我的真实代码中,没有实际的 id!我刚刚补充说清楚,不应该改变顺序。

我怎样才能做到这一点?

编辑:

谢谢你的所有想法。我创建了一个包含所有四种解决方案的 JSPerf。看起来具有两个嵌套 for 循环的版本是迄今为止最快的。你可以自己测试一下:

https://jsperf.com/sort-vs-flatmap/1

标签: javascriptsorting

解决方案


您可以为此使用flatMap和。filter

type请记住,数组中需要有所有可能desiredOrder,否则会丢失一些项目。

const desiredOrder = [4, 2, 3, 1];

let list = [
  {id: 1, type: 2},
  {id: 2, type: 4},
  {id: 3, type: 2},
  {id: 4, type: 1},
  {id: 5, type: 2},
  {id: 6, type: 3}
];

// Run through all types in the order array
// => flat map will turn all the array results of the filter method into a list of elements
//       eg: [...filterResultArray1, ...filterResultArray2, ]
let result = desiredOrder.flatMap(type =>
  // Get all elements that match the type as an array 
  list.filter(l => l.type == type)
);

console.log(result)


推荐阅读