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",
},
];
let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));
console.log(x);
Example 3: javascript sort object by key
function sortObjectByKeys(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
var unsorted = {"c":"crane","b":"boy","a":"ant"};
var sorted=sortObjectByKeys(unsorted);
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];
});
Example 5: js object sort
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
var sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});
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 )