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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With