user248462
user248462

Reputation: 95

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]);

Upvotes: 0

Views: 66

Answers (2)

Oliver
Oliver

Reputation: 1380

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]));

Upvotes: 0

Tibebes. M
Tibebes. M

Reputation: 7548

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)

Upvotes: 2

Related Questions