sort object array descending javascript code example
Example 1: sort array elements in descending order based on object key
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
Example 2: sort array of objects in ascending order in js
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
Example 3: descending order in objects in js
starWarsPeople.map(e=>{
return e
}).sort((a,b)=> b.height - a.height);
Example 4: javascript sort array of objects by key value ascending and descending order
function compareValues(key, order = 'asc') {
return function innerSort(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
return 0;
}
const varA = (typeof a[key] === 'string')
? a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string')
? b[key].toUpperCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return (
(order === 'desc') ? (comparison * -1) : comparison
);
};
}