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.
eg:
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?
Quoting from MDN :
The default sort order is lexicographic (not numeric).
Try this instead:
function merge_arrays(a, b) {
console.log( (a.concat(b)).sort(function(a, b) { return a - b; }).join(" ") );
}
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(" ")
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(" ");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.