0

Why doesn't this sort in numeric order after concat?

var hege = [34, 12];
var stale = [1, 78, 8, 4];
var children = hege.concat(stale).sort(); //1,12,34,4,78,8

http://jsfiddle.net/6kN5H/

Govind Singh
  • 15,282
  • 14
  • 72
  • 106
Squirrl
  • 4,909
  • 9
  • 47
  • 85
  • "The default sort order is according to string Unicode code points." -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – elclanrs Jul 16 '14 at 08:56
  • so how should I sort numerically? – Squirrl Jul 16 '14 at 08:57
  • Thanks for the -1. My bad for thinking sort could possibly due that. I'm sure no one else ever made that mistake. – Squirrl Jul 16 '14 at 09:05
  • 2
    That's the point, http://stackoverflow.com/questions/1063007/arr-sort-does-not-sort-integers-correctly, http://stackoverflow.com/questions/6093874/why-doesnt-the-sort-function-of-javascript-work-well, http://stackoverflow.com/questions/21989665/javascript-array-sort-doesnt-work-on-some-arrays-of-numbers, etc. – elclanrs Jul 16 '14 at 09:19
  • Possible duplicate of [How to sort an array of integers correctly](https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly) – Squirrl Feb 17 '19 at 15:36

3 Answers3

3

the .sort method sorts elements alphabetically

use

.sort(function(a,b){return a - b})

var children = hege.concat(stale).sort(function(a,b){return a - b}); //1,4,8,12,34,78

check this fiddle

Govind Singh
  • 15,282
  • 14
  • 72
  • 106
1

Try this

hege.concat(stale).sort(function(a,b){return (+a)-(+b)})

Here we are converting each value in number & sorting as numbers.

Because by default javascript sort does ordering as string, you have to specify how you want to sort.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
-1
function myFunction() {
    var hege = [34, 12];
    var stale = [1, 78, 8, 4];
    var children = hege.concat(stale).sort((hege, stale) => hege>stale); 
    document.getElementById("demo").innerHTML= children;
}
myFunction();
Sapna
  • 1