With JavaScript how would I increment numbers in an array using a for loop?

I am trying to increment the numbers in the array

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

I try to use

for (var i = 0; i < myArray.length; i++){ myArray[i] + 1; } 

but that doesn't seem to do anything :( please help

8 Answers

You can use map() which will make it quite clean:

var arr = [1,2,3,4]; arr = arr.map(function(val){return ++val;}); console.log(arr);

There's many possibilities to do that, you can use plus equal += like following :

for (var i = 0; i < myArray.length; i++){ myArray[i] += 1; } 

Or simply :

for (var i = 0; i < myArray.length; i++){ myArray[i] = myArray[i] + 1; } 

Hope this helps.


var myArray = [1, 2, 3, 4]; for (var i = 0; i < myArray.length; i++){ myArray[i] += 1; } alert(myArray);

Use the ES6 arrow function:

arr = [1, 2, 3, 4]; new_arr = arr.map(a => a+1); console.log(new_arr);

Assuming your array contains ordered numbers, with increment of size 1, you can also use this code:

var myArray = [1,2,3,4]; myArray.push(myArray[myArray.length - 1] + 1); myArray.shift(); alert(myArray);

Without Es6,

 myArray[i] = myArray[i] + 1; or ++myArray[i] 

Will work.

1

You can use Array constructor to do this.

Using Array.from() method

For Example :

Array.from([1,2,3,4,5], x => x+x); 

That's it. And You can even create empty array with length

Array.from({length:5}, (v, i) => i); 
1

You can use ES6's Array.from() method. The callback is a mapping function, which you can use to add one to each number in the array.

Here the prefix (rather than postfix) increment operator ++ is used in the map function because when you use the increment operator before the operand, the increment occurs before the value is returned, whereas with postfix, the original value will be returned before the operand will be increased (so, an unchanged version of the array would be returned in the case of x++).

function addOne(arr) { return Array.from(arr, x => ++x); } addOne([1, 2, 3]); // [2, 3, 4] 

You can use Array constructor.

Using Array.map() method, fill the series with numbers

For Example :

Array(5 + 1).fill().map((_, index) => index + 1) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like