sort array of dictionaries javascript code example
Example 1: 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) {
return 1
}
return 0
}
books.sort((book1, book2) => {
return compareObjects(book1, book2, 'name')
})
Example 2: javascript sort array of objects by key value
arr.sort((x, y) => x.distance - y.distance);