Home > Software design >  Multiplying elements in arrays using the forEach function
Multiplying elements in arrays using the forEach function

Time:11-22

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.

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);

CodePudding user response:

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);

CodePudding user response:

Numbers was never defined correctly, please see example below.

You can use your mapped array to return the correct data.

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

function multiplyNumbers() {
  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 multiplyArray
}
multiplyArray = (multiplyNumbers());
console.log(multiplyArray);

CodePudding user response:

From the task, it seems like you're supposed to update the given array. With a forEach loop you can reference the array you are looping on along with the index and value

let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
multiplyArray.forEach(function(val, i, arr){
    arr[i] = val*5;
})
  • Related