nodejs sort object by 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: typescript sort array of objects
const list = [
{ color: 'white', size: 'XXL' },
{ color: 'red', size: 'XL' },
{ color: 'black', size: 'M' }
]
list.sort((a, b) => (a.color > b.color) ? 1 : -1)