From what it said, it sounds very simple, but I wasn't succeeded to achieve the perfect result in Chrome (I did it in IE)
So I have an object:
var objs=[
{ name: "water", type: "cold" },
{ name: "tea", type: "hot" },
{ name: "coffee", type: "hot" },
{ name: "choco", type: "cold" }
];
I sorted it by name, ascending and I got the expected result:
- choco,cold
- coffee, hot
- tea, hot
- water, cold
I got the same result both in IE and Chrome,
Then, I sort it again by type, ascending, and my expectation:
- choco, cold
- water, cold
- coffee, hot
- tea, hot
But I only got the expected result in IE, while in Chrome the result was almost the same except that "water" came at the top (it ruins the first sorting)
any general approach idea? (I need to keep it one function call per field, not sorting by multiple fields in one function at the same time)
My sort method was like this:
function SortBy(key,Asc,method){
var GetKey=function(x) {return method ? method(x[key]) : x[key] };
return function(a,b){
var A=GetKey(a), B=GetKey(b);
return ((A<B) ? -1 : ((A>B) ? 1 : 0)) * [-1,1][+!!Asc];
}
}
var sortedObjects=Clone(objs); //clone the current objs
sortedObjects.sort(SortBy("name" , true, function(x){
if (typeof(x)=="string") return x.toLowerCase(); else return x;
}));
objs=sortedObjects; //got the first result
sortedObjects.sort(SortBy("type",true,function(x){
if (typeof(x)=="string") return x.toLowerCase(); else return x;
}));
objs=sortedObjects;
EDITED here is the fiddle (the problem is the "Water"): DEMO
need to keep it one function call per field
? This inefficient