Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing numbers from 1st array if 2nd array match

I have 2 arrays that looks like this:

amountArray = ["200","150","500","100"];
currencyArray = ["EUR","EUR","USD","USD"];

I'd like to sum amounts from 1st array if 2nd array match. Result i'd like to get :

totalAmount = "350 EUR | 600 USD";
like image 746
Kapilraj Parameswararajah Avatar asked Oct 24 '25 00:10

Kapilraj Parameswararajah


1 Answers

You could take a Map for collecting same currencies and get the joined values.

let amounts = ["200", "150", "500", "100"],
    currencies = ["EUR", "EUR", "USD", "USD"],
    result = Array
        .from(
            currencies.reduce(
                (m, c, i) => m.set(c, (m.get(c) || 0) + +amounts[i]),
                new Map
            ),
            ([k, v]) => [v, k].join(' ')
        )
        .join(' | ');

console.log(result);
like image 115
Nina Scholz Avatar answered Oct 26 '25 19:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!