How to set subarray elements?

How do I set elements of subarrays e.g.

var arr = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];
var secondArr = [];
for (let i = 0; i < arr.length; i++)   {
  for (let j = 0; j < arr[i].length; j++) {
     secondArr[i][j] = 5;

When I run it, it throws an error “Uncaught TypeError: Cannot set property ‘0’ of undefined”.
You can do this when the array is only 1d, then why not 2d arrays?

Your secondArr is empty. Javascript does not know that you want that to be an array of arrays, so it throws an error when it tries to set element 0 (or any element) of the nonexistant subarrays.
You might be able to get around this by actually creating the subarrays in the outer loop before trying to set elements of those subarrays.

1 Like

You might also make a copy of arr and use that for secondArr (a real copy using spread or some other method, not just an assignment).

But I’m not really sure what the use case is for the example code you have given. Do you have something specific in mind?

1 Like

I am trying to solve a leetcode question. I am trying to build an array from the original that reverses the subarray elements and also take the inverse of it (e.g if the original array is [[0, 0, 1], [0, 0, 1], [1, 0, 1]], then the output would be [[0, 1, 1], [0, 1, 1], [0, 1, 0]] ). But no worries, the solution provided by @JeremyLT worked for me.