// Array of products with id, name, and price
const products = [
{ id: 3, name: 'Laptop', price: 1200 },
{ id: 1, name: 'Smartphone', price: 500 },
{ id: 2, name: 'Tablet', price: 300 }
];
// Sort the products array by price in ascending order
const sortedProducts = products.sort((a, b) => a.price - b.price);
// Display the sorted products
console.log('Sorted Products:', sortedProducts);
code
JavaScript Sort Array of Objects by Property
This JavaScript code demonstrates how to sort an array of objects (products) based on a numeric property (price). The sort method is used with a custom comparison function to arrange the products in ascending order of their prices. The comments provide explanations for each part of the code.
Array Sorting
Objects
Sort by Property