How pass array name as parameter to reduce (add) function?

39 Views Asked by At

I want to be able to pass an array name to a function that sums all the values of an array. However, I can't get this working with bracket notation the way that I would with an object.

UPDATE: Based on the comments below, I now realize that I can simply pass the array instead of passing it's name as a string. Here is a working example:

function sum(array) {
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    var x = array.reduce(reducer, 0);
    return x;
}

const arrayA = [1, 2, 3, 4];
const arrayB = [1, 2];

var x = sum(arrayA);
var y = sum(arrayB);

console.log('= ' + x);
console.log('= ' + y);

Below are the examples from my original question.

Here is the not working code that shows the syntax I'd like to use:

function sum(array) {
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    var x = [array].reduce(reducer, 0); // bracket notation, but doesn't seem to work
    return x;
}

const array = [1, 2, 3, 4];

var x = sum('array'); // should = 10

console.log('= ' + x);

Here is a working version of a reduce function that isn't passing the array name as a parameter (thus, doesn't suit my needs).

function sum() {
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    var x = array.reduce(reducer, 0);
    return x;
}

const array = [1, 2, 3, 4];

var x = sum();

console.log('= ' + x);

0

There are 0 best solutions below