I have array contains 300elements []; and I want to sum each [I],
for(var i = 0; i<300; i++){
var array2 = arr[i].reduce((prev, next) => (
return prev + next
))
}
it should like that array1 = [1,2,3,4,5,6,7,8,9..] array2 [3,6,10...]
I have array contains 300elements []; and I want to sum each [I],
for(var i = 0; i<300; i++){
var array2 = arr[i].reduce((prev, next) => (
return prev + next
))
}
it should like that array1 = [1,2,3,4,5,6,7,8,9..] array2 [3,6,10...]
var arr = [1,2,3,4,5,6,7,8,9,10,.....]
var array2 = []
// Log to console
for(var i = 1; i<300; i++){
var newArray = arr.slice(0, i+1).reduce((prev, next) => {
return prev + next
})
array2.push(newArray)
}
console.log(array2)
array2 output : [3, 6, 10, 15, 21, 28, 36, 45, 55...]
In your code
this causes an error for two reasons
var array2 = arr[i].reduce((prev, next) => (
return prev + next
))
the reduce()
method is for arrays only and arr[i]
would output a number. Instead you were looking to use the slice()
method.
And to use return
you must use curly braces {}
instead of ()
. Alternatively you could've done arr.slice(0, i+1).reduce((prev, next) => prev + next)
. (see: When should I use a return statement in ES6 arrow functions)