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

85
Visualizações
At what index does the sum reach a certain value

I have an array of numbers and some limit.

const a = [1,2,1,3,4,1,2];
const limit = 5;

What's the most javascripty way of reducing this array to the index such that the sum from the beginning to the index would exceed the limit?

I've done

function findIndex(nums, limit) {
      let s = 0;
      for (let [index, num] of nums.entries()) {
        s += num;
        if (s >= limit) {
          return index;
        }
      }
      return nums.length;
    }
findIndex([1,2,1,3,4,1,2], 5)
3

Is there a more neat way of doing this using reduce or something else?

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

0

As you're after the index, you could look at using the array method .findIndex(). The below code adds to sum for each item in arr, and then checks whether the new accumulated sum value is greater than or equal to the limit. If it is, the callback for findIndex will return true, giving you the index of the item it returned true for. If the callback function to findIndex doesn't return true for any values, it will result in -1, which you can then check before you return to see if you need to return the array length or the found index:

const findIndex = (arr, limit) => {
  let sum = 0;
  const idx = arr.findIndex((num, idx) => (sum+=num) >= limit);
  return idx > 0 ? idx : arr.length; 
}

console.log(findIndex([1,2,1,3,4,1,2], 5));

about 4 years ago · Juan Pablo Isaza Relatório

0

Since you need the

1) index upto which the sum is greater or equal to limit

2) You want to return early as soon as the sum exceeds limit

then you should go for old school for loop. There is no need to accumulate the index and value using nums.entries()

function findIndex(nums, limit) {
  let sum = 0;
  for (let i = 0; i < nums.length; ++i) {
    sum += nums[i];
    if (sum >= limit) return i;
  }
  // Return something explicitely to 
  // indicate that sum can't exceeds limit.
  // You may return -1 if you like
}
console.log(findIndex([1, 2, 1, 3, 4, 1, 2], 5));

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