-3

I am trying to sort this array by price. If the item is on sale then by its onSalePrice and if it is not sale then by its price. I have my current solution below but it doesn't work. Any thoughts??

The 'lowest-price' parameter is indicating toward the value in my option field. This parameter is definitely working okay. The issue is in the conditions that I am sorting with

const products = [
  {
    price: 28.99,
    onSalePrice: 22.99,
    onSale: "True",
  },
  {
    price: 26.99,
    onSalePrice: 22.99,
    onSale: "True",
  },
  {
    price: 24.99,
    onSale: "False",
  },
];

if (sort === "lowest-price") {
        if (products.onSale === "True") {
          tempProducts = products.slice().sort((a, b) => {
            return a.onSalePrice - b.onSalePrice;
          });
        } else if (products.onSale === "False") {
          tempProducts = products.slice().sort((a, b) => {
            return a.price - b.price;
          });
        }
      }

  • 1
    Wouldn’t `const tempProducts = products.slice().sort((a, b) => a.onSalePrice - b.onSalePrice || a.price - b.price)` be easier? See [How to sort an array of objects by multiple fields?](/q/6913512/4642212). – Sebastian Simon Oct 22 '22 at 14:43
  • _it doesn't work_ What exactly isn't working? What is the output you get? – Michel Oct 22 '22 at 14:50
  • Hi Sebastian, that solution doesn't work because it merely sorts by the salePrice and doesn't check whether it is on sale or not – Dan JamesEngineer Oct 22 '22 at 14:54
  • Hi Michel, the array is being sorted according to the price. Which is great. but the issue is, if an item is on sale it is not sorting it according to the price that is on sale so it is not being sorted correctly – Dan JamesEngineer Oct 22 '22 at 14:55
  • @DanJamesEngineer _“it merely sorts by the salePrice”_ — No, that’s wrong. It sorts by `salePrice` first by subtracting one from the other. If the result is `0` or `NaN`, _then_ it sorts by `price`. The result is `NaN` if one of the `salePrice` property lookups reports `undefined`. – Sebastian Simon Oct 22 '22 at 15:45

1 Answers1

0

const products = [
  {
    price: 28.99,
    onSalePrice: 22.99,
    onSale: "True",
  },
  {
    price: 26.99,
    onSalePrice: 22.99,
    onSale: "True",
  },
  {
    price: 24.99,
    onSale: "False",
  },
];

const getPrice = o => o.onSale==='True' ? o.onSalePrice : o.price;
let tempProducts = [...products].sort((a,b) => getPrice(a) - getPrice(b));

console.log(tempProducts);
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27