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

156
Vistas
Given an array of integer numbers, sum this number and all numbers that after it

At the end I get numbers, how to convert it to array?

Example:

Input: 4, 5, 1, 2, 3, -2

Output: [(13, 9, 4, 3, 1, -2)];

function sumNumbers(numbersList) {
  const data = numbersList.forEach((item, index) => {
    const output = numbersList.reduce(
      (acc, c, i) => (index !== i ? (acc += c) : c),
      0
    );
    console.log(result);

    return output;
  });
  return data;
}

sumNumbers([4, 5, 1, 2, 3, -2]);

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

0

Consider replacing the Array.prototype.forEach with Array.prototype.map (since we want the value returned)

function sumNumbers(numbersList) {
  const main = numbersList.map((item, index) => {
    const result = numbersList.reduce(
      (acc, c, i) => (index !== i ? (acc += c) : c),
      0
    );

    return result;
  });
  return main;
}

console.log(sumNumbers([4, 5, 1, 2, 3, -2]))


Explanation:

.forEach returns undefined (docs)

while .map returns "A new array with each element being the result of the callback function." (docs)

about 4 years ago · Juan Pablo Isaza Denunciar

0

The response given by @tibebes-m, an other approach (which reduces complexity) is to iterate back the array backwards, and use only a reduce function (no map)

const sumNumbers = (list) => list
  .reverse()
  .reduce((acc, next, index) => {
      acc.unshift(next + (acc[0] || 0));
      return acc;
  }, []);

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

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