gpt4 book ai didi

javascript - 根据另一个 id 数组对对象数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:02:09 27 4
gpt4 key购买 nike

我有两个数组

a = [2,3,1,4]
b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]

如何根据 ab 进行排序?我想要的输出是

c = [{id: 2}, {id: 3}, {id: 1}, {id: 4}]

我更愿意使用 Ramda 或常规 JS。

最佳答案

您可以为 JavaScript 的 Array#sort 提供自定义比较函数方法。

使用自定义比较函数保证排序顺序:

var sortOrder = [2,3,1,4],
items = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];

items.sort(function (a, b) {
return sortOrder.indexOf(a.id) - sortOrder.indexOf(b.id);
});

MDN :

  • If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).

Hitmands 对上述解决方案做出了非常公正的评论:

This approach is O(n2), and would cause performance issues in big sized lists. Better to build the dictionary first, so that it stays O(n)

上述解决方案对于大输入可能会很慢,因为它使用 indexOf 进行每次比较,而 indexOf 本身就比字典慢 (O(n))查找 (O(1))。

实现 Hitmands 的建议:

let sortOrder = [2,3,1,4],
items = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];

const itemPositions = {};
for (const [index, id] of sortOrder.entries()) {
itemPositions[id] = index;
}

items.sort((a, b) => itemPositions[a.id] - itemPositions[b.id]);

关于javascript - 根据另一个 id 数组对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35538509/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com