ES6组按分区,对象列表排序

时间:2018-08-24 20:35:52

标签: javascript sorting ecmascript-6 grouping partitioning

我正在尝试在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"
   }
 ]

我已经尝试过对分组依据进行操作,但这是对每个姓名和姓氏的手动处理。

_.groupBy(list , {"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;
       },[  [], [], [] ]);

感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分:3)

您可以使用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; }