Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sum up value in array and not all values in array

Tags:

javascript

Right now I am working on this function to litterlay sum up. The array looks for example like this: var array = ['5','2','8']; I want to litterly say array[0] +1 or something like this. I look at reduce but that sums up all the values with each other, that is not what it is supposed to do. What should come out is when sum is 1, and you want the first value in the array. In this case is the first one is 5 : 5 + 1 = 6. Then 6 should come out of it and replace the place of 5 in the array.

This is an example of what I got right now.

var array = ['6','2','5'];
for(var i = 0; i < array.length; i++){
  array = array[i];
  var sum = 1;
  array = sum + array[0];
  console.log(array); 
}
like image 669
MissesA Avatar asked Nov 17 '25 22:11

MissesA


2 Answers

I want to litterly say array[0] +1 or something like this.

Looks like you want to increment all the values by 1.

Try this appoach

var array = ['6','2','5'];
array = array.map( a => String( Number(a) + 1 ) );
console.log(array);

If you want to keep them Number instead of String, then remove the wrapping with String constructor

var array = ['6','2','5'];
array = array.map( a => Number(a) + 1 );
console.log(array);

Edit - Based on comment and question update

no I want to add 1 to only one value in the array and not all of them

What should come out is when sum is 1, and you want the first value in the array.

No need for iteration then

var array = ['6','2','5'];
var sum = 1;
array[ sum - 1 ] = String( Number( array[ sum - 1 ] ) + 1 );
console.log(array);
like image 119
gurvinder372 Avatar answered Nov 19 '25 12:11

gurvinder372


You can use unary plus operator to convert the first element array[0] to a number and than add 1 and finally add '' to make it a string again:

var array = ['6','2','5'];
array[0] = +array[0] + 1 + '';

console.log(array);
like image 44
Yosvel Quintero Arguelles Avatar answered Nov 19 '25 11:11

Yosvel Quintero Arguelles