How to sort an object by price?

  • 0
    How can you sort such an array of objects by price?

    const products = [
        {"term":{
                "2": 
                {
                    "id": "2",
                    "price": "119",
                    "quantity": "1"
                },
              "23":
              {
                    "id": "9",
                    "price": "199",
                    "quantity": "5"
                }
            }
        },
        {"term":{
                "103": 
                {
                    "id": "20",
                    "price": "100",
                    "quantity": "13"
                }
            }
        },
        {"term":{
                "256": 
                {
                    "id": "678",
                    "price": "569",
                    "quantity": "6"
                }
            }
        }, 
    ];


    Tried to sort like this
    but i am getting sorted prices and not object
    const srt = products.map((item) => {
                return Object.keys(item.term).map((key) => {
                    return item.term[key].price;
                })
            })
    console.log('sort', srt.sort((a, b) => a - b))


    in the end I want to get a sorted array of objects at a price
    the first object in the array should be with the lowest price,
    and the last object with the highest price.
    well, from lower price to higher
    JavaScript Anonymous, Mar 30, 2019

  • 1 Answers
  • 0
    products.sort((a, b) => {
    a = Math.min(...Object.values(a.term).map(v => Number(v.price)));
    b = Math.min(...Object.values(b.term).map(v => Number(v.price)));
    return a - b;
    });
    Parker Middleton

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!