I need to sort an array of objects providing a dictionary with keys and their order. Just like this:
var data = [
{ "name": "a", "age": 1, "money": 4 },
{ "name": "f", "age": 4, "money": 1 },
{ "name": "c", "age": 2, "money": 3 },
{ "name": "a", "age": 0, "money": 1},
{ "name": "f", "age": 4, "money": 3 },
{ "name": "c", "age": 1, "money": 4 },
{ "name": "c", "age": 3, "money": 1 }
];
var data = data.multiSort({
name: "asc",
age: "desc",
money: "desc"
});
console.log(data);
/*
{ "name": "a", "age": 1, "money": 4 },
{ "name": "a", "age": 0, "money": 1},
{ "name": "c", "age": 3, "money": 1 }
{ "name": "c", "age": 2, "money": 3 },
{ "name": "c", "age": 1, "money": 4 },
{ "name": "f", "age": 4, "money": 3 },
{ "name": "f", "age": 4, "money": 1 }
*/
I'm totally stuck and I don't get how to achieve this. Lots people point out this simple piece of code but I do not understand how it is supposed to achieve what I'm trying to do. https://github.com/Teun/thenBy.js
This is the code I have right now. I know I'm pretty far from the solution, but I'd appreciate any help to understand how to get there since I need to improve a lot on javascript.
Array.prototype.multiSort = function(sorters){
function getNextSorter(sorters, currentSorterKey) {
var sortersKeys = Object.keys(sorters);
if(!currentSorterKey)
currentSorterIndex = 0;
else
currentSorterIndex = sortersKeys.indexOf(currentSorterKey) + 1;
var key = sortersKeys[currentSorterIndex];
var order = sorters[key];
}
function compare(a, b, key, order) {
var a = a[key];
var b = b[key];
//if both numbers compare them as numbers and not as strings
var numericA = parseFloat(a);
var numericB = parseFloat(b);
if(!isNaN(numericA) && !isNaN(numericB)) {
a = numericA;
b = numericB;
}
//if different compare them with the given order
if(a != b)
return (order == "asc") ? a - b : b - a;
//else compare next key as specified in sorters (if next key is present!)
else
//how to recursively call to get the next compare function?
}
//how to call sort now?
return this;
};