In JavaScript è semplice ordinare un array di oggetti.
Definiamo il seguente codice:
'use strict';
const compare = (key, order = 'desc') => {
return (a, b) => {
if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
return 0;
}
let varA = (typeof a[key] === 'string') ? a[key].toLowerCase() : a[key];
let varB = (typeof b[key] === 'string') ? b[key].toLowerCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return ((order == 'desc') ? (comparison * -1) : comparison);
};
};
Esempio d'uso:
'use strict';
const products = [
{title: 'A', price: 10},
{title: 'B', price: 5},
{title: 'C', price: 8}
];
console.log(products.sort(compare('price', 'asc')));
Output:
[
{title: 'B', price: 5},
{title: 'C', price: 8},
{title: 'A', price: 10}
]