Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Iterating through two arrays at the same time

In Python, I can zip two arrays together and iterate through them at the same time (without using indices). E.g.

list1 = [1, 2, 3, 4]
list2 = [9, 8, 7, 6]

for a, b in zip(list1, list2):
    print(a + b)

will return 10 for four times.

Is this possible in JS?

Also, there is something called enumerate(...) in Python, which takes an iterable as the input, and returns a list of indices and a list of the elements. E.g.

my_list = ["apple", "orange", "banana"]

for index, value in enumerate(my_list):
    print(index, value)

This will return the fruit names with their indices on the left.

What would be the equivalent way to do this in JS?

1 Answer

Steven Parker
Steven Parker
243,160 Points

Here's some JavaScript ways to approximate the same tasks (Python code in comments):

// for a, b in zip(list1, list2):
//     print(a + b)
list1.forEach((a, i) => console.log(a + list2[i]));

// for index, value in enumerate(my_list):
//     print(index, value)
my_list.map((value, index) => console.log(index, value));

And if we define "zip" first, we can make an equivalent to that first one that looks very much like the Python:

var zip = (a,b) => a.map((x,i) => [x,b[i]]);
// for a, b in zip(list1, list2):
for (let [a, b] of zip(list1, list2))
//     print(a + b)
     console.log(a + b);

Did you forget braces or they are optional in this case?

Steven Parker
Steven Parker
243,160 Points

Braces .. for the loop? They are optional, just like with an "if", when there's only one statement involved.

Thanks! Still trying to get used to JS syntax...