Reputation: 267
I am trying to merge and sort 2 arrays in numerical order.
function merge_arrays(a, b) {
console.log( (a.concat(b)).sort().join(" ") );
}
This works fine with single digits in an array, but it doesn't sort numbers with double digits properly.
e.g.:
a: [2, 3, 7, 8, 8,]
b: [7, 8, 13]
will output as: 13 2 3 7 7 8 8 8
Am I missing something?
Upvotes: 0
Views: 1590
Reputation: 1221
Try this:
c = a.concat(b)
c == [2,3,7,8,8,7,8,13]
c.sort() == [13,2,3,7,7,8,8,8]
This is because, when not provided with a comparison function, sort automatically converts the elements of the list it is sorting to strings. In string land "13" < "2".
Check out the sort documentation.
So what you probably want is something like this:
function compare_number(a,b) {
return a - b;
}
a.concat(b).sort(compare_number);
And to fully answer your question:
a.concat(b).sort(compare_int).join(" ");
Upvotes: 0
Reputation: 3962
http://www.w3schools.com/jsref/jsref_sort.asp
See that section Note: When numbers are sorted alphabetically, "40" comes before "5".
To perform a numeric sort, you must pass a function as an argument when calling the sort method.
The function specifies whether the numbers should be sorted ascending or descending.
Meaning This
function numOrdA(a, b){ return (a-b); }
and your code :
a.concat(b)).sort(numOrdA).join(" ")
Upvotes: 0