eliotte
eliotte

Reputation: 3

Loop thought a multi dimensional array

I try to return a multidimensional array into a function to iterate it but I'm not sure what's wrong with my logic

const arr = [[1,2], [3,4],[5,6]]
for(let i = 0; i < thirdInterval.length-1; i++){
    getNumbers(thirdInterval[i], thirdInterval[i+1])
}

The result that I want to achieve is return the first element into the first argument of the function and the second element of the array into the second argument of the function.

Upvotes: 0

Views: 48

Answers (3)

Ori Drori
Ori Drori

Reputation: 191976

You are iterating an array with sub-arrays, which means that thirdInterval[i] contains two items. You can get the items using the indexes thirdInterval[i][0] and thirdInterval[i][1], but since you're calling a function with those values, you can use spread instead - getNumbers(...thirdInterval[i]).

In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.

Demo:

const thirdInterval = [[1,2],[3,4],[5,6]]

const getNumbers = console.log // mock getNumbers

for (let i = 0; i < thirdInterval.length; i++) {
  getNumbers(...thirdInterval[i])
}

Upvotes: 0

iJamesPHP2
iJamesPHP2

Reputation: 534

const arr = [[1,2][3,4][5,6]];

for (var i = 0; i < arr.length; i++;) {
    func(arr[i][0], arr[i][1];
}

Upvotes: 0

ROOT
ROOT

Reputation: 11622

What you are doing here is looping through the array and getting only the array at the index i, e.g arr[0] which is [1,2]. and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])

to access the first and second elements you should address them like the following:

for(let i = 0; i < thirdInterval.length-1; i++){
    getNumbers(thirdInterval[i][0], thirdInterval[i][1])
}

Upvotes: 1

Related Questions