javascript sort array with objects
var array = [
{name: "John", age: 34},
{name: "Peter", age: 54},
{name: "Jake", age: 25}
];
array.sort(function(a, b) {
return a.age - b.age;
}); // Sort youngest firstconst 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')
})
// 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'}
Also in JavaScript:
- mutable array methods in javascript
- how to make fake binary
- select a form by name jquery
- react native function
- nodejs http get request to external server
- geojson longitude latitude order
- db.json
- google pay payment gateway for react js project
- change font js
- javascript get date
- in object transform translate property concat with rotate value angular 7
- javascript number length
- dynamically change css class with javascript
- ajax status code
- local storage in js
- javascript combine objects
- express error middleware
- node open file
- redirect with javascript
- javascript how to pass an action back in a function
- replace white spaces javascript
- passport middleware check if authenticated
- factory function javascript
- javascript group array of objects lodash