Javascript. Array .sort() Method Returns Different Results For Chrome And Firefox If Array Contains Duplicate Numbers
I have array containing random numbers. When I trying to sort this array via .sort() method, the result is different if array contains duplicate numbers. The code below works diffe
Solution 1:
It works with a proper return value.
var array = [1,2,3,4,5,6,7,8,9,2,15,3,4,5,1,2,3,4,0,2,3];
array.sort(function(a, b) {
return a - b;
});
console.log(array);
array.sort(function(a, b) {
return (a & 1) - (b & 1) || a - b;
});
console.log(array);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Solution 2:
Since sort() is not necessarily stable, you need to save the position of an element before sorting and use it as compare parameter if the value is equal, if you want to keep the position in the result array . But the problem in your case is, you have multiple values and can't just look up the position in the starting-array. You need to wrap your values in objects:
var values= [1,2,3,4,5,6,7,8,9,2,15,3,4,5,1,2,3,4,0,2,3];
var wrappedValues = [];
//first create wrapped valuesfor(var i = 0;i < values.length;i++){
wrappedValues.push({value : values[i], index : i});
}
//now sort wrapped values
wrappedValues.sort(function(a, b) {
var result = a.value % 2 - b.value % 2;
if(result == 0){
return a.index - b.index;
}
return result;
});
//now unwrappe the values:var unwrappedValues = [];
wrappedValues.forEach(function(entry) {
unwrappedValues.push(entry.value);
});
console.log(unwrappedValues );
btw. part of your Problem is in the compare function from the answer you provided:
returna % 2-b % 2 || a-b;
this function is sorting ascending in || a - b
- part
Post a Comment for "Javascript. Array .sort() Method Returns Different Results For Chrome And Firefox If Array Contains Duplicate Numbers"