I need to sort the nrArray
array:
var nrArray = nrArray.sort();
What the above does is this:
["1", "17", "206", "22", "3", "6"]
I need this:
["1", "3", "6", "17", "22", "206"]
I need to sort the nrArray
array:
var nrArray = nrArray.sort();
What the above does is this:
["1", "17", "206", "22", "3", "6"]
I need this:
["1", "3", "6", "17", "22", "206"]
Pass in a comparison callback and use parseInt
like
var arr = ["1", "17", "206", "22", "3", "6"];
arr.sort(function(a, b){
return parseInt(a)- parseInt(b);
});
console.log(arr);
Update
You actually dont need parseInt
as a/b
will be auto-converted to numbers. This is because you are subtracting and javascript performs the necessary type conversion. However, the same cannot be said for a + b
as this is string concatenation.
It is because by default the sort() method will do a string based comparison
compareFunction
Optional. Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
var nrArray = ["22", "17", "8", "206", "1", "3", "6"];
nrArray.sort(function(a, b) {
return a - b;
});
console.log(nrArray)
Applied from SO: Sort Array Elements (string with numbers), natural sort
You need a natural sort. A good generic natural sort providing the comparison to sort that will also work in case the strings also contain letters:
function naturalCompare(a, b) {
var ax = [], bx = [];
a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });
while(ax.length && bx.length) {
var an = ax.shift();
var bn = bx.shift();
var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if(nn) return nn;
}
return ax.length - bx.length;
}
var nrArray = nrArray.sort(naturalCompare);
Yes because your create array of strings not number. [1, 17, 206, 22, 3, 6] should work fine. moreover no need to write
var nrArray = nrArray.sort();
nrArray.sort(); changes the original array itself