我正在尝试在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(list , {"name": "john"});
我还尝试过使用数组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;
},[ [], [], [] ]);
非常感谢您的帮助。谢谢。