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

  • see: [Creating an array of cumulative sum in javascript](https://stackoverflow.com/questions/20477177/creating-an-array-of-cumulative-sum-in-javascript) – pilchard May 04 '22 at 21:02

1 Answers1

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)

pilchard
  • 12,414
  • 5
  • 11
  • 23
Bas
  • 1,353
  • 3
  • 7
  • 18
  • 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! –  May 04 '22 at 22:03