Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort doesn't work after push?

What am I doing wrong here: Same results in IE9 and FF.

function TestArrayOperationsClick()
{
  function sortNums(a, b)
  {
    return a - b;
  }
  var array = [6, 4, 2, 8];
  console.log("Array 1: " + array); 
  array.sort(sortNums);
  console.log("Sort 1: " + array);
  array.push([1, 5, 10]);
  console.log("Array 2: " + array);
  array.sort(sortNums);
  console.log("Sort 2: " + array);
}

Output:

LOG: Array 1: 6,4,2,8 

LOG: Sort 1: 2,4,6,8 

LOG: Array 2: 2,4,6,8,1,5,10 

LOG: Sort 2: 2,4,6,8,1,5,10 <- not sorted.
like image 909
Dean Avatar asked Jan 30 '14 14:01

Dean


2 Answers

For array.push(...), you should be passing individual arguments, not an array:

array.push(1, 5, 10);

For which the final output would then be:

Sort 2: 1,2,4,5,6,8,10 

Otherwise, the result of your push is actually this:

[2,4,6,8,[1,5,10]]

, though it's not showing clearly when you do console.log.

Edit: As Jonathan mentioned, if you're looking to append an array of items, .concat() is the way to go.

like image 88
Herman Schaaf Avatar answered Sep 18 '22 11:09

Herman Schaaf


.push() doesn't combine Arrays like the following appears to expect:

array.push([1, 5, 10]);

Instead of pushing the individual values, it pushes the 2nd Array itself, resulting in:

[ 2, 4, 6, 8, [ 1, 5, 10 ] ]

To append one Array onto another, you can use .concat():

array = array.concat([1, 5, 10]);
like image 36
Jonathan Lonowski Avatar answered Sep 20 '22 11:09

Jonathan Lonowski