apgujeong
apgujeong

Reputation: 99

Using forEach() for 2 arrays

How do I use forEach() for 2 arrays simultaneously?

array1.forEach(each => {
    if (each.open > each.close) {
        drawShape(x,y)

I want to include also data from another array of the same length. Do I use zip for this?

Upvotes: 1

Views: 66

Answers (1)

Seth Lutske
Seth Lutske

Reputation: 10686

One way is to use the index argument of forEach, which gives the index of the current item being iterated over. You can use that to access the item of another array at the same index.

array1.forEach( (each, index) => {
    if (each.open > each.close) {
        console.log(array2[index])
    }
})

This is of course assuming they are the same length, otherwise this will break.

Upvotes: 2

Related Questions