DEV Community

Brett Fuller
Brett Fuller

Posted on

Using a single for each loop or map to go over multiple arrays

This is a quick read but I just wanted to jot it down since I haven't seen it talked about much. In Javascript, the .forEach method and the .map method both have a second parameter that you can add that makes it so you can actually get both the item and its index.


const arr1 = [1, 2, 3, 4, 5];
const arr2 = [2, 3, 4, 5, 6];
arr1.forEach( (a, i) => console.log(a + arr2[i]) );
// alternatively, if you want to store it;
const arr3 = arr1.map( (a, i) => a + arr2[i] );

I do know that there are some flaws in the way I implemented the above code since if the arrays aren't the same length you will get NaN at the point where the shorter array ends. There are ways to guard against this such as using a ternary operator to check against the shorter array. Here is a working example of that.

In the code above, that little i makes a wonderful addition to the language. This feature is one that I often wish I could have in other languages because the amount of times I wish I had been able to get the index of the item I was using while being able to use forEach instead of for loop has been through the roof lately. I understand why languages like C# don't have it (it is enumerating over it in a way that has no concept of indices), but man would it be nice to have this syntactical sugar.

Top comments (3)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.