-1

How would I be able to create a product sort system using JavaScript

I have this Array:

let products = [
      {
        productName: "Product1",
        price: 40
      },
      {
        productName: "Product2",
        price: 50
      },
      {
        productName: "Product3",
        price: 20
      },
      {
        productName: "Product4",
        price: 10
      },
      {
        productName: "Product5",
        price: 10
      },
      {
        multiple other products with prices
      },
];

I want to sort the products by price, so that the products with the lowest price are shown at the top of the page, and the products with the highest price are shown at the bottom of the page. How would I do this?

1 Answers1

0

You can pass a callback to Array#sort that subtracts the prices.

let products=[{productName:"Product1",price:40},{productName:"Product2",price:50},{productName:"Product3",price:20},{productName:"Product4",price:10},{productName:"Product5",price:10},];
products.sort((a, b) => a.price - b.price);
console.log(products);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80