-2

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...]

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank a lot! All day I try to do this ! In jQuery I use simple method a=[]; for (I = 0; I <10; I++){ r=0; r = + r + are[I] ; a.push(r); but here it does not work. Gracias. If I only could give you "this answer is useful". Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.