lateralus500
lateralus500

Reputation: 159

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

Upvotes: 14

Views: 79563

Answers (10)

Robert Dundon
Robert Dundon

Reputation: 1168

You can now do this with Array.reduce() (MDN doc):

array = [23,10]
array.reduce((accumulator, currentValue) => accumulator + currentValue)
// Returns 33

Upvotes: 0

InSync
InSync

Reputation: 10437

An ES6 functional solution would be:

myArray.forEach((_, i) => myArray[i]++);
// or
myArray.forEach((_, i, a) => a[i]++);

This is basically the same as Zakaria Acharki's answer. The arguments passed to the arrow function by .forEach() are the element themselves, the index and a reference to the array. Since the values are, in this particular situation, numbers, the _ variable holds a copy of the value, and incrementing _ won't affect anything outside our function's scope. However, myArray[i] or a[i] is a reference, which works as expected when we increment it.

Try it:

console.config({ maximize: true });

const myArray = [1, 2, 3, 4];
myArray.forEach((_, i) => myArray[i]++);
console.log(myArray);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

When this proposal is accepted (currently it is at stage 3) and supported by browsers, you can do something like this:

myArray.keys().forEach(i => myArray[i]++);

Array#keys() returns an iterator that yields the array's keys, which are its numeric indices. .forEach() works the same as Array#forEach(); the difference between this example and the example above (not the methods themselves) is that the first argument is now also the index, so we wouldn't need the second one.

Try it (as of May 2023, this doesn't work):

console.config({ maximize: true });

const myArray = [1, 2, 3, 4];
myArray.keys().forEach(i => myArray[i]++);
console.log(myArray);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Upvotes: 0

徐万文
徐万文

Reputation: 1

const arr1 = Array.from(Array(5), (_, index) => index);
console.log(arr1); // 👉️ [ 0, 1, 2, 3, 4 ]

const arr2 = Array.from(Array(5), (_, index) => index + 1);
console.log(arr2); // 👉️ [ 1, 2, 3, 4, 5 ]

Upvotes: 0

Harish Kumar
Harish Kumar

Reputation: 11

You can use Array constructor.

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

For Example :

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

Upvotes: 1

baao
baao

Reputation: 73221

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

Upvotes: 13

nCardot
nCardot

Reputation: 6587

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]

Upvotes: 0

chelladurai89
chelladurai89

Reputation: 21

Without Es6,

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

Will work.

Upvotes: 1

Julian Gong
Julian Gong

Reputation: 390

Use the ES6 arrow function:

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

Upvotes: 13

xxxmatko
xxxmatko

Reputation: 4142

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

Upvotes: 2

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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

Upvotes: 10

Related Questions