Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put elements at the begginning of an array with filter and sort - javascript

I have an array of objects where I want to find certain elements and put them in the beginning or the array. I started doing it by using the find function and it worked but now because there can be more than one element I switch to filter function however, now it stopped working, how can I fix this?

Input example:

colors= [
   {name: "green", popular: true},
   {name: "yellow", popular: false},
   {name: "red", popular: true},
   {name: "black", popular: true},
   {name: "red", popular: true}
]

Function:

sort(colors) {
    let red= colors.filter(color=> colors.name === "red")

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

    return colors
}

Expected Output:

colors= [
   {name: "red", popular: true},
   {name: "red", popular: true},
   {name: "green", popular: true},
   {name: "yellow", popular: false},
   {name: "black", popular: true}
]

By using filter red variable returns an array instead of an object like with find

like image 978
user9875 Avatar asked Dec 31 '22 21:12

user9875


1 Answers

You could just sort red parts to top.

const
    colors= [{ name: "green", popular: true }, { name: "yellow", popular: false }, { name: "red", popular: true }, { name: "black", popular: true }, { name: "red", popular: true }];

colors.sort((a, b) => (b.name === "red") - (a.name === "red"));

console.log(colors);
like image 139
Nina Scholz Avatar answered Jan 05 '23 18:01

Nina Scholz