-1

I want to add one to each element of my array. I tried:

myArray=[1,2,3]
myArray.map(a=>a+=1) // tried a++ and a=a+1 too
console.log(myArray) // return [ 1 , 2 , 3 ]

it doesn't worked... so i did that :

myArray=[1,2,3]
mySecondArray=[]
myArray.map(a=>mySecondArray.push(a+1))
console.log(mySecondArray) // return [ 2, 3, 4 ]

So it worked, but I don't anderstand why the first one didn't. Can you explain me why?

4
  • 4
    Array.map returns the mapped array. You can do arr = arr.map(...) if you want to set the array to its mapped version. Commented Jun 12, 2020 at 9:48
  • Because map doesn't change the original array. It returns another one. Commented Jun 12, 2020 at 9:48
  • Try myArray = myArray.map(a=>a+=1). map returns a new array. Commented Jun 12, 2020 at 9:48
  • You can use myArray.forEach((_, i) => myArray[i] += 1) to mutate the array, but I wouldn't recommend it. Instead replace the current variable with a mapped version of the array, like shown in the answers below. Commented Jun 12, 2020 at 10:06

3 Answers 3

1

The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method, that's why your first approach didn't work.

let myArray = [1,2,3];
myArray = myArray.map(x => x + 1);
console.log(myArray);
Sign up to request clarification or add additional context in comments.

Comments

0

You need to equate it back :

myArray = myArray.map(a => a+1);
console.log(myArray)

output --- > [2, 3, 4]

2 Comments

a => a + 1 is enough
yes, my bad, have changed it
0

Currently, you are not storing the instance.

Store the instance in some array,

let myArray=[1,2,3]
myArray = myArray.map(a=>a+1);
console.log(myArray);

1 Comment

There is no reason to use += it only introduces confusion. I suggest changing it to a +.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.