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

151
Visualizações
Remove the last element of an array while the sum of the array is bigger than a specific number

I'm trying to remove the last items of an array as long as the sum of the array is higher than a limit. The code I have works but seems to cause slow downs or crash. I was wondering if there's a more elegant solution.

let array = [166, 157, 251, 171, 191];
let limit = 400;

for (
  let sum = array.reduce((a, b) => a + b); sum > limit; sum = array.reduce((a, b) => a + b)
) {
  array.pop();
}

console.log(array);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You don't need to sum the entire array each time through the loop. Calculate the sum once at the beginning. Then subtract the element that you removed from the sum.

let array = [166, 157, 251, 171, 191];
let limit = 400;

for (let sum = array.reduce((a, b) => a + b); sum > limit; sum -= array.pop()) {}

console.log(array);

about 4 years ago · Juan Pablo Isaza Relatório

0

This solution will achieve the result in O(n)

You can achieve the result If you loop over the array and remember the last total i.e currentTotal and stop the iteration and break out from the loop if

currentTotal + val > limit

else add the current value in currentTotal and push that element in the result array.

let array = [166, 157, 251, 171, 191];
let limit = 400;

let currentTotal = 0;
const result = [];

for (let val of array) {
  if (currentTotal + val > limit) {
    break;
  }
  result.push(val);
  currentTotal += val;
}

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

To improve efficiency, as Barmar stated, you can calculate the sum once and update it in each loop iteration. I believe a while loop expresses this idea the most clearly:

const arr = [166, 157, 251, 171, 191];
const limit = 400;

let sum = arr.reduce((a, b) => a + b)
while (sum > limit) {
  const lastNum = arr.pop();
  sum -= lastNum;
}

console.log(arr)

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