Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiplying elements in arrays using the forEach function

I’m currently learning about arrays and the different ways to manipulate them. I was asked to: "multiply 5 to the given array using the forEach function"

Here is my code so far.

It looks as if everything works when I console.log in the forEach function, but when I log the console for the array it’s read as undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];

function multiplyNumbers() {
  let numbers;
  multiplyArray.forEach(function(element) {
    let fiveTimesNum;
    fiveTimesNum = (element * 5);
    element = fiveTimesNum;
    console.log(element)
  });
  console.log('The array(element) value is read out correctly, but when I console log the array its value is ↓')
  return numbers
}
multiplyArray = (multiplyNumbers());
console.log(multiplyArray);

>Solution :

If you want to change the array multiplyArray in place you can it like this:

let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];

multiplyArray.forEach(function(n,i,a){a[i]=5*n;});

console.log(multiplyArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading