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