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

88
Vistas
Running sum of the input array in Javascript

I want to build a function that

  1. takes an array of numbers as an input.
  2. calculates the running sum of the numbers in the input array.
  3. returns a new array that contains the running sum.

For example, if I call this function with the input of [1,2,3,4], the output should be [1,3,6,10]. However, when I run my code, it returns an empty array.

The following is the code I got so far.

function sumOfArray(nums) {
  var output = [];        // tip: initialize like let output = [nums?.[0] ?? 0];
  for(let i = 1 ; i < nums.length ; i++) {
    nums[i] = nums[i] + nums[i-1];
    output.push(nums[i]);
  }
  return output;
};

console.log(
  'calling sumOfArray([1,2,3,4])',
  sumOfArray([1,2,3,4])
);

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

const input =  [1,2,3,4]

const theFunctionYouWannaWrite = (acc, v) => {
  acc.push(v + (acc[acc.length - 1] || 0))
  return acc;
}

const output = input.reduce(theFunctionYouWannaWrite, [])

console.log(output)

if you want to use it with for

const input =  [1,2,3,4]

const theFunctionYouWannaWrite = (acc, v) => {
  acc.push(v + (acc[acc.length - 1] || 0))
  return acc;
}

function sumOfArray(nums) {

  var output = [];

  for(let i = 0 ; i < nums.length ; i++) {
    theFunctionYouWannaWrite(output, nums[i])
  }

  return output;
};

console.log(sumOfArray(input))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Just add first item in array initialization and everything works fine.

function sumOfArray(nums) {
  var output = [nums[0]];        // tip: initialize like let output = [nums?.[0] ?? 0];
  for(let i = 1 ; i < nums.length ; i++) {
    nums[i] = nums[i] + nums[i-1];
    output.push(nums[i]);
  }
  return output;
};

console.log(
  'calling sumOfArray([1,2,3,4])',
  sumOfArray([1,2,3,4])
);

about 4 years ago · Juan Pablo Isaza Denunciar

0

let 
  sum = 0,
  nums = [1, 2, 3, 4],
  res = [];

nums.forEach((item, index, arr) => {
  sum += arr[index];
  res.push(sum);
});

console.log(res);

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