I'm using this solution to sort an array of objects. This is the function:
function sortJsonArrayByProperty(objArray, prop, direction){
if (arguments.length<2) throw new Error("sortJsonArrayByProp requires 2 arguments");
var direct = arguments.length>2 ? arguments[2] : 1; //Default to ascending
if (objArray && objArray.constructor===Array){
var propPath = (prop.constructor===Array) ? prop : prop.split(".");
objArray.sort(function(a,b){
for (var p in propPath){
if (a[propPath[p]] && b[propPath[p]]){
a = a[propPath[p]];
b = b[propPath[p]];
}
}
// convert numeric strings to integers
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
return ( (a < b) ? -1*direct : ((a > b) ? 1*direct : 0) );
});
}
}
It's a great solution.
But I have a problem with a column that store prices in this format:
950,75 1234,99 500,00
So, I have values with a comma separating decimals. Then, instead of this sequence:
222,55 550,00 2000,99 3000,00
I'm getting:
2000,99 222,55 3000,00 550,00
I'm trying to do some modification at this part:
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
But that isn't working. What's wrong?