Increment Values In An Array In JavaScript

To increment values in an array in JavaScript, you can use any of the following methods –

  1. Use Array.map()
  2. Use Array.forEach()

Let’s understand each function in detail below.

increment values in an array in javascript

Array.map() To Increment Values In An Array In JavaScript

The Array.map() method is used to create a new array with the results of calling a provided function on every element in the given array.

We can use this method to increment values in an array by a given amount.

For example, if we have an array of numbers and we want to increase each value by 10, we can do that using the map() method like this –

var arr = [-5, 10, 15, 20];

var newArray = arr.map(function(value){

  return value + 10;

});

console.log(newArray); //[5, 20, 25, 30]

There is another way to use the map() function –

var arr = [1, 2, 3];

const newArray = arr.map(element => element+1);

console.log(newArray); //[11, 12, 13]

Here, we used an arrow function to increment the values by 1.

Array.forEach() To Increment Values In An Array In JavaScript

The forEach() method is used to execute a given function for each element in an array.

We can use this method to increment values in an array as well.

For example, below we have used forEach() method to increment the values of each element of an array by 10 –

var arr = [1, 2, 3];

arr.forEach(function(value, index) {

  arr[index] = value + 1;

});

console.log(arr); //[2, 3, 4]

As you can see from the output, we have successfully incremented the values of each element in our array by 1.

You can also use arrow functions with forEach() method to increment the values in an array as well –

var arr = [1, 2, 3];

arr.forEach((value, index) => {

  arr[index] = value + 1;

});

console.log(arr); //[2, 3, 4]

Both the map() and forEach() methods are widely used to increment values in an array in JavaScript.

You can choose any one of these methods as per your needs and requirements.

Increment Value Of A Single Element In An Array In JavaScript

In the above examples, we saw how to increment values of all elements in an array by a given amount.

But what if you want to increment the value of a single element in an array?

For example, let’s say you have an array of numbers and you want to increment the value of the first element by 1.

To do that, you can use the following code –

var arr = [-5, 10, 15, 20];

arr[1] += 1;

console.log(arr); //[-5, 11, 15, 20]

As you can see from the output, we have successfully incremented the value of the first element by 1.

You can use this same technique to increment the value of any element in an array by a given amount.

This brings us to the end of this article where we have learned how to increment the values in an array in JavaScript.

I hope you found this article helpful. Thanks for reading!

Leave a Reply