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

88
Views
Split An Array into sub arrays that each sub array sum value not exceed in JavaScript

I would like to create sub arrays of [10,10,10,10,10,10,10,10,10,4,4,4] that sum of each sub array is not greater than 100, so the result should be [[10,10,10,10,10,10,10,10,10,4,4],[4]]

I tried below, but not work not sure where the problem is at

   const arr=[10,10,10,10,10,10,10,10,10,4,4,4]

  
    const result=[]

    let sum=0
    let temp=[]

    for(let i=0; i<arr.length;i++){
      if(sum+arr[i]<=100){
        sum+=arr[i]
        temp.push(arr[i])
      }else{
         result.push(temp)
         sum=0
         temp.length=0

         temp.push(arr[i])
         sum+=arr[i]
      }
    }

console.log(result) //[ [ 4 ] ]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

After you push temp onto result you need to create a new temp array, not set the length of the old array to 0, because you have a reference to that array in result. So change temp.length = 0 to temp = [].

And at the end of the loop you need to push the final temp onto result.

const arr = [10, 10, 10, 10, 10, 10, 10, 10, 10, 4, 4, 4]
const result = []

let sum = 0
let temp = []

for (let i = 0; i < arr.length; i++) {
  if (sum + arr[i] <= 100) {
    sum += arr[i]
    temp.push(arr[i])
  } else {
    result.push(temp)
    sum = 0
    temp = []

    temp.push(arr[i])
    sum += arr[i]
  }
}

if (temp.length > 0) {
  result.push(temp);
}

console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

First: don't use temp.length=0

Second: you're not creating a new array inside else, so basically you're editing what you have pushed inside result

Inside else, after pushing into result, just use temp = []

On top of that, you shall check if there are additional items inside temp and the end of the loop, and do one more push into result

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!