Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda