Cannot use push on array

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.

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

Thank you!
and sorry for that

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:

1 Like

Oh, probably the first option approach to what I want

Thank :smiley:

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.

Thank

I understand the issue

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

once again, thank guys :smiley: