Jmainol
Jmainol

Reputation: 437

destructuring inside a reduce method

I would like to know if it´s possible to destructuring directly inside a reduce method on JS. I´m trying to do something like this:

With this 2D array:

currency = [
    ["PENNY", 0.01],
    ["NICKEL", 0.05],
    ["DIME", 0.01],
    ["QUARTER", 0.25],
    ["ONE", 1],
    ["FIVE", 5],
    ["TEN", 10],
    ["TWENTY", 20],
    ["ONE HUNDRED", 100]
];

I would like to get the sum of all amounts. I mean something like this:

const [curr, amount] = change;

return change.reduce(amount => amount + b);

Even better would be destructuring the currency array directly inside the reduce method´s callback.

Upvotes: 0

Views: 2069

Answers (3)

Yanjan. Kaf.
Yanjan. Kaf.

Reputation: 1755

let currency = [
    ["PENNY", 0.01],
    ["NICKEL", 0.05],
    ["DIME", 0.01],
    ["QUARTER", 0.25],
    ["ONE", 1],
    ["FIVE", 5],
    ["TEN", 10],
    ["TWENTY", 20],
    ["ONE HUNDRED", 100]
];
console.log(currency.reduce((acc, cur) => {return acc + cur[1]},0))

Upvotes: 0

Valentin Ivanchikov
Valentin Ivanchikov

Reputation: 93

There are many variants. Without changing structure of data i this:

return currency.map(element => element[1]).reduce((acc, curr) => acc + curr);

Upvotes: 0

Pointy
Pointy

Reputation: 413866

If you want to sum the amounts:

const sum = currency.reduce((total, [_, amount]) => total + amount, 0);

Each sub-array is destructured into the denomination name and amount.

Upvotes: 2

Related Questions