how to sort some array of objecs in ascending order and some object in descending order using javascript code example
Example 1: sort array of objects javascript
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: sort array of objects in ascending order in js
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
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
);
};
}