javascript - 按给定的数字序列对 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 循环的版本是迄今为止最快的。你可以自己测试一下:
解决方案
您可以为此使用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)
推荐阅读
- mysql - 使用node.js将数据插入mysql时如何解决错误
- c - C: 我有一个简单的快餐交易程序,如何自动打印订购食物的收据?
- c# - 如何获取属于本地系统组的域用户 SID
- ibm-mobilefirst - MFP 8.0 - 登录后间歇性的 invalid_scope 错误
- view - SwiftUI - if let 有条件闭包的替代方案
- c# - 如何将指令引用到 MySql.Data.MySqlClient 以连接 mysql 数据库
- python - 如何为 Python 设置 IDE(如 VS Code、Sublime text 3)?
- php - php中的分页限制数据但不在下一页显示
- javascript - 没有客户端请求的 django 响应
- html - 图像调整大小是否需要媒体查询或计算以在网格布局上强制没有容器边距?