Home > front end >  I am trying to order the array by most valued, from lowest to highest, but those with 0 value are or
I am trying to order the array by most valued, from lowest to highest, but those with 0 value are or

Time:07-23

I am trying to order the array by most valued, from lowest to highest, but those with 0 rating are ordered after the highest valued, and then from highest to lowest by price

const product = [
  {mostValued:5, price: 5},
  {mostValued:0, price: 14},
  {mostValued:0, price: 58},
  {mostValued:3, price: 33},
  {mostValued:0, price: 25},
  {mostValued:4, price: 47},
]
 // code
product.sort((a, b) =>
      a.mostValued == b.mostValued 
        ? b.price - a.price
        : a.mostValued - b.mostValued
);

Those with 0 stars should be sorted after, highest to lowest by price, so the expected output would be

[
  {mostValued:3, price: 33},
  {mostValued:4, price: 47},
  {mostValued:5, price: 5},
  {mostValued:0, price: 58},
  {mostValued:0, price: 25},
  {mostValued:0, price: 14}
];

CodePudding user response:

Easiest way would be to coalesce 0s (and other falsy values?) to Infinity:

product.sort((a, b) =>
    (a.mostValued || Infinity) - (b.mostValued || Infinity) ||
    b.price - a.price
);

Alternatively, specifically give those with mostValued == 0 a priority:

product.sort((a, b) =>
    (a.mostValued == 0) - (b.mostValued == 0) ||
    a.mostValued - b.mostValued ||
    b.price - a.price
);
  • Related