1

I'm trying to get arguments ( fom second arg ) when running a js file in node then sum them.

var args = 0;

process.argv.reduce((a, b, c) => {
    if (c > 1) {
        console.log(+a + +b);
        this.args += +a + +b;
    }
    return a
}, 0);
console.log(args)

In result I get 0 as sum when I run node exlearnyounode.js 12 4 6 but I'm expecting 22

infodev
  • 4,673
  • 17
  • 65
  • 138

1 Answers1

2

In your code, you are assuming a to be accumulator, b to be the element from collection, c to be the index of the element. Instead, you should just pass just two arguments to reduce, first is the accumulator, next is the element yielded from collection process.argv; it doesn't give the index relative to the collection.

This should do it:

console.log(process.argv.slice(1).reduce((acc, a) => acc + a))

slice(1) will give the arguments except first:

var arr = [0, 3, 2, 1]
console.log(arr.slice(1))
console.log(arr.slice(1).reduce((acc, a) => acc + a))
kiddorails
  • 12,961
  • 2
  • 32
  • 41