I have a javascript array which looks like this:
var data = ["size64_tolPercent0.01_best", "size256_tolPercent0.01_best", "size256_tolPercent0_worst", "sizemax_tolPercent0_worst", "size1518_tolPercent0_worst", "size64_tolPercent0.01_worst", "size512_tolPercent0.01_worst", "size1518_tolPercent0.01_worst", "size256_tolPercent0_best"] etc
I want to sort this array :
- by the substring "best" and "worst".
- by the tolPercents 0 and 0.01
- sizes (64, 256, 512, 1518, max).. it would be good if the sizes are sorted by strings since it contains a "max" keyword..
So, we end up with a result array which looks like this:
["size64_tolPercent0_best", "size256_tolPercent0_best", "size512_tolPercent0_best", "size1518_tolPercent0_best", "sizemax_tolPercent0_best", "size64_tolPercent0.01_best", "size512_tolPercent0.01_best", "size1518_tolPercent0.01_best", "size64_tolPercent0_worst", "size256_tolPercent0_worst", "size512_tolPercent0_worst", "size1518_tolPercent0_worst", "sizemax_tolPercent0_worst"] etc
I am able to sort the strings using one of the methods but not all.
Here's what I've tried so far, I'm doing it wrong I'm sure, just need some help in the right direction. Doing it for 1 and 3 now:
var someLargeValue = 10000000;
data.sort(function(x,y){
var xp = x.substr(getPosition(x, '_', 2) + 1, x.split("_").pop().length);
var yp = y.substr(getPosition(y, '_', 2) + 1, y.split("_").pop().length);
return xp == yp ? 0 : xp < yp ? -1 : 1;
});
data.sort(function(x,y){
var xp = x.substr(4, getPosition(x, '_', 1) - 4);
var yp = y.substr(4, getPosition(y, '_', 1) - 4);
if(xp === "max") {
xp = someLargeValue;
}
if(yp === "max") {
yp = someLargeValue;
}
xp = parseInt(xp);
yp = parseInt(yp);
return xp == yp ? 0 : xp < yp ? -1 : 1;
});
function getPosition(str, m, i) {
return str.split(m, i).join(m).length;
}
But i'm afraid the code i'm trying is doing the sorting sequentially.. so what the first custom sort method is overridden by the second, I think?
Any help much appreciated.
best-worstfirst, thenpercentnext, thensizelast. Note that your cannot accurately sort this without some sort of priority ranking.