Cannot use push on array

Cannot use push on array
0.0 0

#1
function largestOfFour(arr) {
  var array = [];
  
  for(var i = 0; i < arr.length; i++) {
    arr[i].sort(function(a,b) {
      return b - a;
    });

    array[i].push(arr[i][0]);
    
  }
  return array;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

The above code always give me an error "Type Error : Cannot read Property ‘push’ of undefined

It seems like the program consider the “array” is not an Array Object, so I cannot use push there, just wondering why?

Thank

PS:I already solved this challenge, just want to know why the above issue happened.


#2

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#3

Thank you!
and sorry for that


#4

You’re trying to push into a specific index (array[i]). This doesn’t want to work… probably because array[i] hasn’t been declared an array yet.

But it looks like you only want the number, so I found two quick options that work:

// remove the index and just push to array
array.push(arr[i][0]);

// use a direct assignment to that index
array[i] = arr[i][0];

Only use one or the other. :slight_smile:


#5

Oh, probably the first option approach to what I want

Thank :smiley:


#6

To follow up, you can only push onto an array that already exists. If you have [], you can push to it. If you have anything else (including undefined), it probably won’t work.


#7

Thank

I understand the issue

I tried to push an element to an non-array object (array[i])

once again, thank guys :smiley: