Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!