2

I have an array

peeps = [{name: "Mike", age: 31},{name: "Dave", age: 31},{name: "Delta", age: 31},{name: "Clint", age: 31}] 

And I need to sort them by an arbitrary order of

newOrder = ['Delta', 'Dave', 'Mike', 'Clint']

How would I reference newOrder to sort peeps, also bear in mind the data in peeps is not guaranteed to have all the names in newOrder

2
  • 1
    please add your code. what have you tried? Commented Nov 26, 2020 at 9:01
  • The name will be known, newOrder will be static but peeps might have all the names or only 1 of the names in peeps. I've tried to figure out a way to do it by sorting alphabetically and then reversing the order but I cant figure it out. Commented Nov 26, 2020 at 9:03

2 Answers 2

4

const peeps = [
  { name: 'Mike', age: 31 },
  { name: 'Dave', age: 31 },
  { name: 'Delta', age: 31 },
  { name: 'Clint', age: 31 }
];
const newOrder = ['Delta', 'Dave', 'Mike', 'Clint'];

peeps.sort((a, b) => newOrder.indexOf(a.name) - newOrder.indexOf(b.name));

console.log(peeps);

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

Comments

2

This is one way:

const peeps = [{name: "Mike", age: 31},{name: "Dave", age: 31},{name: "Delta", age: 31},{name: "Clint", age: 31}];
const newOrder = ['Delta', 'Dave', 'Mike', 'Clint'];

const notInNewOrder = peeps.filter(i => !newOrder.includes(i.name));

const response = newOrder.map(n => ({...peeps.find(peep=> peep.name === n)}));

console.log(response.concat(notInNewOrder));

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.