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

Viewed 132

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

3 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);

You can use filter() twice and use spread operator to order the arrays correctly

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

const res = [...colors.filter(x => x.name === "red"), ...colors.filter(x => x.name !== "red")];
console.log(res)

You can use reduce and unshfit. Inside reduce call back put all the elements which dont have red name and in another array put elements which have red name. The use unshift to add the elements at the beginning

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

let colArr = [];

let arr = colors.reduce((acc, curr) => {

  if (curr.name === 'red') {
    colArr.push(curr)
  } else {
    acc.push(curr)
  }
  return acc;
}, []);

colArr.forEach((item, index) => {
  arr.unshift(item)
});

console.log(arr)

Related