The wrong way to loop through two arrays
Let us assume we are given two arrays like so:
The two arrays contain company names and their ticker symbols (respectively). We wish to loop over them and print output such as:
Here’s a first attempt at doing it through nested loops.
The output will be:
Oops! This is running a nested for loop with each element of the first array paired with each element of the second array. This is obviously not what is intended.
Use the forEach method with the index argument
Because we are looking for corresponding elements it suffices to loop through one array using the forEach method but using two arguments (the element as well as the index). The forEach method applied to array1 can be used to return both the element and the index of the element. We use the returned index value to index into the second array and find the corresponding element. Then we use both these pieces of information to print the composite message. Here is the program to do so:
The output of the program is, as expected:
Use the Javasript Array map() method
Here the function being applied has two arguments (only the first argument is required). The first argument is company which is the element that we are iterating over in the array. The second argument is the index of the corresponding element. Thus, for each element in array1, we print the company followed by the ticker symbol. The output is, as before:
Use the collect.js library
Which of the three approaches above is your favorite?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.