sort array of object in javascript code example
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: 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;
});
Example 3: sort array of objects javascript by value
let orders = [
{
order: 'order 1', date: '2020/04/01_11:09:05'
},
{
order: 'order 2', date: '2020/04/01_10:29:35'
},
{
order: 'order 3', date: '2020/04/01_10:28:44'
}
];
console.log(orders);
orders.sort(function(a, b){
let dateA = a.date.toLowerCase();
let dateB = b.date.toLowerCase();
if (dateA < dateB)
{
return -1;
}
else if (dateA > dateB)
{
return 1;
}
return 0;
});
console.log(orders);
Example 4: javascript sort object
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 28800
};
var sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});