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);
}
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With