1

I want to do it with the forEach loop but I can't do it, what I want to do is the following

For example i have the first array:

let numbersA = [4,5,6,7,8];

Then i have the last array:

let numbersB = [2,3,4,5,6];

The expected output:

4 * 2 = 8

4*3 = 12

4 * 4 = 16

4 * 5 = 20

4 * 6 = 24

and now comes the second multiplication of the first array of the second number:

5 * 2 = 10

5 * 3 = 15

5 * 4 = 20

5 * 5 = 25

5 * 6 = 30

How can I get this result, I want to do it with the forEach loop, using arrow functions but I got stuck

3
  • 1
    Where did you get stuck? Commented Mar 12, 2022 at 16:37
  • I got stuck with forEach loop because I don't know if I have to do a loop or two to do the multiplications @TusharShahi Commented Mar 12, 2022 at 16:39
  • It might look like bad code, but just use two nested for loops. You can do the exact same thing with .forEach() too, but that can cause problems in some rare senarios. If you absolutely need to use .forEach(), then try array1.forEach(item1 => array2.forEach(item2 => doSomething(item1 * item2))) Commented Mar 12, 2022 at 16:43

3 Answers 3

1

let numbersA = [4,5,6,7,8];
let numbersB = [2,3,4,5,6];
numbersA.forEach(a => numbersB.forEach(b => console.log(a * b)));

Sign up to request clarification or add additional context in comments.

1 Comment

Please consider adding some explanation. It would be very helpful for a beginner.
0

You could use Template Literals to print out the equation:

let numbersA = [4, 5, 6, 7, 8];
let numbersB = [2, 3, 4, 5, 6];
numbersA.forEach(a => {
    numbersB.forEach(b => console.log(`${a} * ${b} = ${a * b}`));
});

Comments

0

You can do it like this using nested forEach:

numbersA.forEach((itemA) => {
   numbersB.forEach((itemB) => {
       console.log(itemA * itemB);
   });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.