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

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

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 Denunciar

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 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