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

159
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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