Find item in array and set as first index

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

Find item in array and set as first index

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?

Admin Posts: 805
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'}]