Skip to content
Advertisement

How to push new elements to an array with undefined index in JavaScript

I want to create array once and then just push values to it with any index , but i get Cannot read property 'push' of undefined error

I have following scenario

var neg = [];

I want to use push randomly with any index

neg[0].push([1,2]);

or

neg[22].push([1,2]);

right now I want to define manually like neg[0] = []; , Is there any one way where i can just push to any index i want ?

Advertisement

Answer

Here’s a quick way to do exactly what you want.

var arr = [];

(arr[0]=[]).push([1,2]);

console.log(arr)

Also it’s safer to check if an array already exists at this index, otherwise it will be replaced with an empty array – the above code will replace the array with an empty one if it already exists.

// creates an array at index 0 only if there's no array at this index.
// pushes an array of [1, 2] to the existing array at 0 index
// or the newly created empty one.
(arr[0] || (arr[0] = [])).push([1, 2]);;

var arr = [];

arr[0] = [1];

(arr[0]||(arr[0]=[])).push(2,3);

console.log(arr)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement