gpt4 book ai didi

javascript - ES6 groupBy,分区,排序对象列表

转载 作者:行者123 更新时间:2023-11-29 10:28:41 26 4
gpt4 key购买 nike

我试图在 ES6 中找到一种优雅的方式来根据指定的值对对象数组进行排序。场景如下:

const list = [
{
"name": "john",
"lastName": "smith"
}, {
"name": "tony",
"lastName": "smith"
}, {
"name": "tony",
"lastName": "grey"
}, {
"name": "mary",
"lastName": "smith"
}, {
"name": "john",
"lastName": "x"
}, {
"name": "tom",
"lastName": "y"
}
, {
"name": "mary",
"lastName": "x"
}
]

let orderList = [{"name":["john","mary"]}, {"lastName":["x"]}];

因此,基本上按姓名 (John, Mary) 对结果进行排序,然后按 lastName(x) 对结果进行排序,但姓名排序仍然优先。结果应如下所示:

[
{
"name": "john",
"lastName": "x"
}, {
"name": "john",
"lastName": "smith"
}, {
"name": "mary",
"lastName": "x"
}, {
"name": "mary",
"lastName": "smith"
}, {
"name": "tony",
"lastName": "smith"
}, {
"name": "tony",
"lastName": "grey"
}, {
"name": "tom",
"lastName": "y"
}
]

我已经尝试过使用 group by 做一些事情,但这是针对每个名字和姓氏的手动过程。

_.groupBy(列表, {"name": "john"});

我也尝试过使用 array reduce 进行试验,但似乎找不到好的动态解决方案。

const sortArr = ['john', 'mary'];
const sortedList= list.reduce((result, element) => {
let index = sortArr.findIndex(x => x === element.name);
result[index !== -1
? index
: result.length - 1].push(element);
return result;
},[ [], [], [] ]);

感谢任何帮助。谢谢

最佳答案

你可以使用 Array#sort并采用迭代方法首先按 name 排序,然后按 lastName 排序。

该提案检查属性是否在数组中,并通过获取索引的增量将这些值排序到顶部。重复此操作,直到增量不为零或订单数组结束为止。

为了获得增量,一个 Array#indexOf进行搜索,如果未找到项的值 -1 被替换为 Infinity,因为必须将此项排序到数组的末尾。找到索引的项目根据索引排序。

为了加快排序速度,具有单个键/值对的对象被转换为具有键和值的数组。

var list = [{ name: "john", lastName: "smith" }, { name: "tony", lastName: "smith" }, { name: "tony", lastName: "grey" }, { name: "mary", lastName: "smith" }, { name: "john", lastName: "x" }, { name: "tom", lastName: "y" }, { name: "mary", lastName: "x" }],
orderList = [{ name: ["john", "mary"] }, { lastName: ["x"] }],
order = orderList.map(o => (k => [k, o[k]])(Object.keys(o)[0]));

list.sort((a, b) => {
var d;
order.some(([k, v]) =>
d = (v.indexOf(a[k]) + 1 || Infinity) - (v.indexOf(b[k]) + 1 || Infinity)
);
return d;
});

console.log(list);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - ES6 groupBy,分区,排序对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52011372/

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