Move two element of an array to the front - Javascript I want to move two element of my array to the beginning.
This solution works but I would like to know a better approach since using sort() twice is probably not the best.
Array Input:
colors = [{name: yellow}, {name: blue}, {name: green}, {name: red}, {name: orange}]

JS Function:
sort(){
let green= colors.find(color=&gt; color.name === &quot;green&quot;)
let red= colors.find(color=&gt; color.name === &quot;red&quot;)

colors.sort(function(x,y){ return x == red? -1 : y == red? 1 : 0; });
colors.sort(function(x,y){ return x == green? -1 : y == green? 1 : 0; });
}

Output:
colors = [{name: green}, {name: red}, {name: yellow}, {name: blue}, {name: orange}]

PS: I want green to always the above red
Find the index of the green and red items, then remove them from the array with splice. Then you can make a properly ordered array by combining the removed items with the rest of the items in the original array:


const colors = [{name: 'yellow'}, {name: 'blue'}, {name: 'green'}, {name: 'red'}, {name: 'orange'}]
const removeColor = colorToRemove =&gt; (
  colors.splice(
    colors.findIndex(({ name }) =&gt; name === colorToRemove),
    1
  )[0]
);
const green = removeColor('green');
const red = removeColor('red');
const newColors = [green, red, ...colors];
console.log(newColors);



Or, without mutation (it's good to avoid mutation when not necessary, it can make code a bit more predictable in most cases):


const colors = [{name: 'yellow'}, {name: 'blue'}, {name: 'green'}, {name: 'red'}, {name: 'orange'}]
const getColor = colorToRemove =&gt; colors.find(({ name }) =&gt; name === colorToRemove);
const green = getColor('green');
const red = getColor('red');
const newColors = [green, red, ...colors.filter(({ name }) =&gt; name !== 'green' &amp;&amp; name !== 'red')];
console.log(newColors);



Also note:

String literals require delimiters. {name: yellow} won't work - you want {name: 'yellow'}.
If you aren't going to reassign a variable name (most of the time you should be able to avoid reassignment), always use const. Only use let when you must reassign.
For readability, better to indent your code when entering a new block (such as a function).