I am trying to sort the array of objects
based on change
property.
Below is the sort function, the strange part is the price when below 100
it's not getting sorted properly. I want the array of objects to be sorted by asc or desc
order by either change or name
.
const data = [{
"id": 74368,
"account": "Gerald Wehner",
"change": "186.00"
},
{
"id": 55998,
"account": "Augusta Koelpin",
"change": "277.00"
},
{
"id": 3044,
"account": "Austyn Bradtke",
"change": "473.00"
},
{
"id": 50305,
"account": "Lesly Boyer",
"change": "56.00"
},
{
"id": 20324,
"account": "Marietta Lynch",
"change": "707.00"
},
{
"id": 40233,
"account": "Eriberto Haley",
"change": "923.00"
}
];
sort = (arr, field, order, cond) => {
const fn = cond ?
function(x) {
return cond(x[field])
} :
function(x) {
return x[field]
};
order = !order ? 1 : -1;
return arr.sort(function(a, b) {
return a = fn(a), b = fn(b), order * ((a > b) - (b > a));
})
}
console.log(sort(data, 'change', true, false))