How to access an element in each array?

Viewed 80

Let's assume that a random array has given:

let myArray = [[1, 2, 3, 5], [3, 4, 5], [2, 5]];

I want to access each element in array like this:

[myArray[0][0], myArray[1][0], myArray[2][0]] // [1, 3, 2]
[myArray[0][0], myArray[1][0], myArray[2][1]] // [1, 2, 5]
[myArray[0][0], myArray[1][1], myArray[2][0]] // [1, 4, 2]
[myArray[0][0], myArray[1][1], myArray[2][1]] // [1, 4, 5]
...
[myArray[0][3], myArray[1][2], myArray[2][1]] // [5, 5, 5]

like this

I know I can do this by using for loop, but the given array may change. Array length and data may different at each time. I want to solve this even if the given array is different. How can I solve this?

Sorry I'm not a English native speaker.

4 Answers

You can use .forEach

const arr = [[1, 2], [3, 4, 5], [6, 7], [8]];
arr.forEach((item) => {
  item.forEach((child) => {
    console.log(child);
  });
})

You can use flat() just for that, it will works for any array depth:

const myArray = [[1, 2, 3, 5], [3, 4, 5], [2, 5]].flat();
const deepArray =  [1, 1, [2, 2], [[3, [4], 3], 2]].flat()

// then you can access every array element with a simple foreach
myArray.forEach(element => console.log(element))
deepARray.forEach(element => console.log(element))

Here's a jsfiddle that show how to use it

myArray.length tells you how many elements it has.

Similarly, myArray[0].length tells you how many elements the first one has, and so on.

You can use that to control your loops.

Related