user9875
user9875

Reputation: 133

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

Upvotes: 4

Views: 307

Answers (3)

brk
brk

Reputation: 50326

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)

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36584

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)

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386670

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

Upvotes: 8

Related Questions