I am trying to figure out an elegant way in ES6 to sort an array of objects based on specified values. Here's the scenario:
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"]}];
So, basically sort the result by the names(John, Mary) and then sort that result by lastName(x), but the name sorting still takes precedence. The result should look like this:
[
{
"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"
}
]
I have already tried doing something with group by, but it's a manual process for each name and last name.
_.groupBy(list , {"name": "john"});
I also tried experimenting with array reduce, but can't seem to find a good dynamic solution.
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;
},[ [], [], [] ]);
Any help is appreciated. Thanks