sort array of objects by key value code example
Example 1: sort by object property javascript
let list = [
{
name: "world"
},
{
name: "hello",
},
];
// This doesn't account for if names are the same between objects
let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));
console.log(x);
/*
[
{
name: "hello",
},
{
name: "world"
},
];
*/
Example 2: javascript sort array of objects by key value
arr.sort((x, y) => x.distance - y.distance);
Example 3: javascript sort object by key
function sortObjectByKeys(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
var unsorted = {"c":"crane","b":"boy","a":"ant"};
var sorted=sortObjectByKeys(unsorted); //{a: "ant", b: "boy", c: "crane"}
Example 4: sort array of objects javascript by value
let orders = [
{
order: 'order 1', date: '2020/04/01_11:09:05'
},
{
order: 'order 2', date: '2020/04/01_10:29:35'
},
{
order: 'order 3', date: '2020/04/01_10:28:44'
}
];
console.log(orders);
orders.sort(function(a, b){
let dateA = a.date.toLowerCase();
let dateB = b.date.toLowerCase();
if (dateA < dateB)
{
return -1;
}
else if (dateA > dateB)
{
return 1;
}
return 0;
});
console.log(orders);
Example 5: sort array of objects javascript by key value
myArray.sort(function(a, b) {
return a.distance - b.distance;
});
Example 6: sort() object values javascript
list.sort((a, b) => (a.color > b.color) ? 1 : (a.color === b.color) ? ((a.size > b.size) ? 1 : -1) : -1 )