Example 1: sort array of object js
const books = [
{id: 1, name: 'The Lord of the Rings'},
{id: 2, name: 'A Tale of Two Cities'},
{id: 3, name: 'Don Quixote'},
{id: 4, name: 'The Hobbit'}
]
books.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
Example 2: 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 3: 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)
Example 4: sort array of objects by string property value
function compareFirstNames( a, b ) {
if ( a.first_name < b.first_name ){
return -1;
}
if ( a.first_name > b.first_name ){
return 1;
}
return 0;
}
var people =[
{"first_name":"Carol", "age":29},
{"first_name":"Anna", "age":32},
{"first_name":"Bob", "age":32}
];
people.sort( compareFirstNames ); //people is now sorted by first name from a-z
Example 5: javascript sort array of object by property
function sortByDate( a, b ) {
if ( a.created_at < b.created_at ){
return -1;
}
if ( a.created_at > b.created_at ){
return 1;
}
return 0;
}
myDates.sort(sortByDate);//myDates is not sorted.
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 )