Page 1 of 1

Find item in array and set as first index

Posted: 24 Nov 2020, 06:49
by Marius
Say I have the following array of persons:

Code: Select all

const arr =[{name: 'Glenn'}, {name: 'Rob'}, {name: 'Ronald'}]
And I want to find a certain person (name) in this array, and put it as the first index in the array if it exist.
Like so:

Code: Select all

// Rob is now first index
const arr =[{name: 'Rob'}, {name: 'Glenn'}, {name: 'Ronald'}]
How can I achieve this in a simple way?

Find item in array and set as first index

Posted: 24 Nov 2020, 09:09
by Admin
You could sort the array with the sort() method.
This approach moves all objects with the wanted 'name' to top.

Code: Select all

const arr =[{name: 'Glenn'}, {name: 'Rob'}, {name: 'Ronald'}];
let first = 'Rob';

arr.sort((a, b) => (b.name == first) - (a.name == first));

console.log(arr);  // [{name: 'Rob'}, {name: 'Glenn'}, {name: 'Ronald'}]