Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
How loop through array.reduce()?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!