var homes = [
{ city: 'A', price: 2, id: 0 },
{ city: 'A', price: 3, id: 2 },
{ city: 'A', price: 3, id: 1 },
{ city: 'A', price: 2, id: 5 },
{ city: 'B', price: 1, id: 6 },
{ city: 'B', price: 1, id: 0 }
];
console.log(sortMutiKeys(homes, 'city ASC', 'price DESC', 'id DESC'));
function sortMutiKeys(array, ...filters) {
var calcSortNumberDESC = (a, b, key) => b[key] - a[key];
var calcSortNumberASC = (a, b, key) => a[key] - b[key];
var calcSortStringASC = (a, b, key) => a[key] > b[key] ? 1 : -1;
var calcSortStringDESC = (a, b, key) => a[key] < b[key] ? 1 : -1;
var sortNumberOrString = (a, b, keyOrder) => {
if (keyOrder !== undefined) {
var [key, order] = keyOrder.split(' ');
if (!isNaN(a[key]) && !isNaN(b[key])) {
if (order == 'ASC') return calcSortNumberASC(a, b, key);
else if (order == 'DESC') return calcSortNumberDESC(a, b, key);
} else {
if (order == 'ASC') return calcSortStringASC(a, b, key);
else if (order == 'DESC') return calcSortStringDESC(a, b, key);
}
}
}
return array.sort((a, b) => {
var index = 0;
var valuesEqual = (a, b, keyOrder) => {
var [key, order] = keyOrder.split(' ');
if (a[key] === b[key]) index++;
return a[key] === b[key];
}
while(index < filters.length) {
if (!valuesEqual(a, b, filters[index])) {
return sortNumberOrString(a, b, filters[index]);
}
}
return sortNumberOrString(a, b, filters[index]);
});
}