Let's say we have a product objects as follows:
let products = [
{
name: "Keyboard"
price: 177,
},
{
name: "Book"
price: 29,
},
{
name: "Chair"
price: 90,
}
];
The following statement sorts the products array by the price in ascending order:
products.sort((a, b) => {
return a.price - b.price;
});
To display the products, use the forEach() method:
products.forEach((e) => {
console.log(`${e.name} ${e.price}`);
});
Output:
Book 29
Chair 90
Keyboard 177