Home > database >  Given an array of integer numbers, sum this number and all numbers that after it
Given an array of integer numbers, sum this number and all numbers that after it

Time:11-27

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]);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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]))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>


Explanation:

.forEach returns undefined (docs)

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

CodePudding user response:

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)

    function sumNumbers(list) {
        return list
            .reverse()
            .reduce((acc, next, index) => {
                acc.unshift(next   (acc[0] || 0));
                return acc;
            }, []);
    };
    
    console.log(sumNumbers([4, 5, 1, 2, 3, -2]));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related