C Hyman
C Hyman

Reputation: 33

JavaScript array.forEach(()) -iterate, change and return new numbers in a new array

I want to return an array, changeArray, with each element in "array" + 2.

I'm getting an empty "changeArray."

var array = [1, 2, 3, 4];

function changeArray(array){
  var newNums = [];
  array.forEach(function(number){
    number = number + 2;
    console.log(number);
    //return(newNums);
  });return(newNums);
}changeArray(array);

Thanks Everyone for your great answers. They really help. I was expected to use .forEach and "return" the new array. I agree .map would be best, but ... Thank you so much!!

Upvotes: 0

Views: 76

Answers (2)

Bondan Sebastian
Bondan Sebastian

Reputation: 1016

The proper function for this task is .map() indeed.

But you can still use your function with some modification.

    var array = [1, 2, 3, 4];

    function changeArray(inputArray){
      var newNums = inputArray.slice();
      newNums.forEach(function(number, index){
        newNums[index] = number + 2;
      });
  return(newNums);
    }
console.log(changeArray(array));

Explanation

First of all, you coded changeArray() to always return an empty array.

See var newNums = [];, then return(newNums);.

While you use forEach() against array variable.

Second, you should read more about forEach() here.

And if you notice, i use .slice() to copy the values of inputArray into newNums.

It's just kind of good practice to ensure inputArray not modified by the function.

Upvotes: 0

adeneo
adeneo

Reputation: 318362

Array.map would be the proper tool for that job

var array = [1, 2, 3, 4];
    
var newNums = array.map(x => x + 2);

console.log(newNums);


The reason the code isn't working, is because you can't really return from a forEach like that, you'd have to push to the array in each iteration

var array = [1, 2, 3, 4];

function changeArray(array) {
  var newNums = [];
  
  array.forEach(function(number) {
    newNums.push( number + 2 );
  });
  
  return newNums;
}

var result = changeArray(array);

console.log(result);

Upvotes: 4

Related Questions