Contentop
Contentop

Reputation: 1261

Sorting currently sorts with respect to other parameters. How to sort according to one specific parameter in javascript?

When sorting array according to a parameter, it sorts it with dependence on another parameter. I would like to ignore the parameter and sort according to my parameter exactly.

I have created an helper function that sorts my array according to my parameter and it works like the following:

For example I have name and price and my array is like so

[{name:"A", price:5},{name:"A", price:70},{name:"A", price:12},{name:"A", price:576}, {name:"C", price:300}.{name:"C", price:899}, {name:"B", price:12}, {name:"B", price:40}, {name:"B", price:15}]

After sorting for price I get: [{name:"A", price:576},{name:"A", price:70},{name:"A", price:12},{name:"A", price:5}, {name:"C", price:899}.{name:"C", price:300}, {name:"B", price:40}, {name:"15", price:12}, {name:"B", price:8}]

I would like for it to ignore the name and just sort according to price... 899,576,300,70...

This is the helper function that sorts according to a parameter of my choosing:

const propComparator = (propName) =>
    (a, b) => a[propName] == b[propName] ? 0 : a[propName] < b[propName] ? -1 : 1

What I do is add items to a set, then after a couple of for loop finishes that adds items to the set I am turning it into an array and sort like so:

let topArray = Array.from(topSet).sort(propComparator('price'));

Upvotes: 2

Views: 147

Answers (1)

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

Your code runs as expected for me:

var topSet = [
    { name: "A", price: 5 },
    { name: "A", price: 70 },
    { name: "A", price: 12 },
    { name: "A", price: 576 },
    { name: "C", price: 300 },
    { name: "C", price: 899 },
    { name: "B", price: 12 },
    { name: "B", price: 40 },
    { name: "B", price: 15 }
];
var propComparator = function (propName) {
    return function (a, b) {
        return a[propName] == b[propName] ? 0 : a[propName] < b[propName] ? -1 : 1;
    };
};
var topArray = Array.from(topSet).sort(propComparator('price'));

console.log(topArray.map(function (a) { return JSON.stringify(a); }).join(",\n"));

Upvotes: 1

Related Questions