js sort array of objects by key value code example
Example 1: typescript sort array of objects
const list = [
{ color: 'white', size: 'XXL' },
{ color: 'red', size: 'XL' },
{ color: 'black', size: 'M' }
]
list.sort((a, b) => (a.color > b.color) ? 1 : -1)
Example 2: javascript sort array of objects by key value
arr.sort((x, y) => x.distance - y.distance);
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: sort array of objects javascript by key value
myArray.sort(function(a, b) {
return a.distance - b.distance;
});
Example 5: sort() object values javascript
list.sort((a, b) => (a.color > b.color) ? 1 : (a.color === b.color) ? ((a.size > b.size) ? 1 : -1) : -1 )
Example 6: js sort array of object by key
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
if(sortOrder == -1){
return b[property].localeCompare(a[property]);
}else{
return a[property].localeCompare(b[property]);
}
}
}