1

Hello guys I have a task on sort. Here is the deal: I have an array

arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}]

and sort sequence list sortSequence = ['dad','mom','bro'] so according this list I need an output array to be equal

arr = [{role:'dad', name:'d'}, {role:'mom', name:'a'}, {role:'bro', name: 'c'}]

How can use sort method to do this?

const sortAccordingList = (list, arr) => {
    //... ?
}
4
  • 1
    Sort expects you to return a number. So if you take the difference between the index of the first elements role inside the sortSequence and the index of the second elements role, you know if first comes before second or not. Commented Jun 29, 2018 at 14:01
  • let s = sortSequence.reduce((p, c, i) => (p[c] = i, p), {}); arr.sort(({role: a}, {role: b}) => s[a] - s[b]); Commented Jun 29, 2018 at 14:04
  • I think this was already answered here Commented Jun 29, 2018 at 14:12
  • Yeah, thanks, I searched, but didn't find it, sorry. Commented Jun 29, 2018 at 14:14

1 Answer 1

2

You can use indexOf to get the index of the role

var sortSequence = ['dad', 'mom', 'bro'];
var arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}];

arr.sort((a, b) => sortSequence.indexOf(a.role) - sortSequence.indexOf(b.role));

console.log(arr);


You can also make sortSequence as an object. This will make it easier to get the sort sequence. Like:

var sortSequence = {dad:1,mom:2,bro:3};
var arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}];

arr.sort((a, b) => sortSequence[a.role] - sortSequence[b.role]);

console.log(arr);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.