Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda