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"
},
];
*/
how to sort an array of objects by a property value in javascript
let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));
Posted by: Guest
on June-06-2021
17
javascript sort array of objects
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'}
]
compareObjects(object1, object2, key) {
const obj1 = object1[key].toUpperCase()
const obj2 = object2[key].toUpperCase()
if (obj1 < obj2) {
return-1
}
if (obj1 > obj2) {
return1
}
return0
}
books.sort((book1, book2) => {
returncompareObjects(book1, book2, 'name')
})
// Result:
// {id: 2, name: 'A Tale of Two Cities'}
// {id: 3, name: 'Don Quixote'}
// {id: 4, name: 'The Hobbit'}
// {id: 1, name: 'The Lord of the Rings'}
Posted by: Guest
on February-25-2020
11
javascript sort array of object by property
functionsortByDate( a, b ) {
if ( a.created_at < b.created_at ){
return-1;
}
if ( a.created_at > b.created_at ){
return1;
}
return0;
}
myDates.sort(sortByDate);//myDates is not sorted.
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems
resetting your password contact us
Check Your Email and Click on the link sent to your email