Neu JavaScript-Objektsortierung: Benutzerdefinierte Sortierung basierend auf Objekteigenschaften


24. September 2022
I'm working on a JavaScript project where I have a set of objects and I need to sort them based on certain properties of the objects. Each object represents a product and has properties such as “Price”, “Rating” and “Name”. I want to sort this array by the Price property in ascending order and for products with the same price by the Rating property in descending order.

Here is a simplified example of the array:
const products = [
    { name: 'Product A', price: 25, rating: 4.5 },
    { name: 'Product B', price: 15, rating: 3.8 },
    { name: 'Product C', price: 25, rating: 4.2 },
    { name: 'Product D', price: 20, rating: 4.0 },

I want to sort this array so that the products are sorted first by "Price" in ascending order and then for products with the same price by "Rating" in descending order. I tried to find the answer on several websites but couldn't manage. Could you provide a JavaScript code snippet showing how this custom sorting is achieved and explain the key concepts and functions used in the code? Many thanks for your help!