Hello I have a textbox having values like
<input type="hidden" value="2,1,4,5,3,6,7,8,9,10,11,12" class="sortvalues" id="1_1_parent">
Now what I want to take the value of this textbox, want to split the values to array and then as last result I need a sorted array.
What I have done.
allsortedValues = $(".sortvalues").val();
allsortedValues = allsortedValues.split(",");
allsortedValues = allsortedValues.sort();
When I check the array
console.log(allsortedValues);
It shows
1,10,11,12,2,3,4,5,6,7,8,9
Sorting array as 1, 10, 11, 12, 2.....
I have even used
allsortedValues = allsortedValues.split(",").map(function(x){return parseInt(x)});
before applying sort and in other case I have even used parseInt
like
for(var i = 0; i < allsortedValues.length; i++) {
allsortedValues[i] = parseInt(allsortedValues[i]);
}
before applying sort but in all cases result is same. Will some one guide what am I doing wrong?
You'll have to pass in a comparator function that converts the strings to numbers:
allsortedvalues = allsortedvalues.sort(function(a,b) {
return (+a) - (+b);
});
If there's a chance that some of your array entries aren't nicely-formatted numbers, then your comparator would have to get more complicated.
The construction (+a)
involves the unary +
operator, which doesn't do anything if a
is already a number. However if a
is not a number, the result of +a
will be either the value of a
when interpreted as a number, or else NaN
. A string is interpreted as a number in the obvious way, by being examined and parsed as a string representation of a number. A boolean value would be converted as false -> 0
and true -> 1
. The value null
becomes 0
, and undefined
is NaN
. Finally, an object reference is interpreted as a number via a call to its valueOf()
function, or else NaN
if that doesn't help.
It's equivalent to use the Number constructor, as in Number(a)
, if you like. It does exactly the same thing as +a
. I'm a lazy typist.
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.
To compare numbers instead of strings, the compare function can simply subtract b from a:
function compareNumbers(a, b)
{
return a - b;
}
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With