Summing numbers from 1st array if 2nd array match

Viewed 84

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";
9 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);

Store your data in a hashmap with the currencies as keys. Then while looping through your amounts, if the key exists, add to the existing sum.

At the end, convert back to an array and print.

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

const result = {};

amountArray.forEach((amt, idx) => {
  const amountInt = parseInt(amt, 10);
  const currency = currencyArray[idx];
  const existingTotal = result[currency] || 0;
  
  result[currency] = existingTotal + amountInt;
});

const resultArray = Object.keys(result).map(key => `${result[key]} ${key}`);

const totalAmount = resultArray.join(' | ');

console.log(totalAmount);

You could do this

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

var res = {}

currencyArray.forEach((elem, index)=>{
  res[elem] =  res[elem] ? parseInt(res[elem]) + parseInt( amountArray[index]) : parseInt(amountArray[index])
});

console.log(res);
var totalAmount = '';
for(var key in res){
  totalAmount += ` ${res[key]} ${key} |`;
}
   console.log(totalAmount.substr(0, totalAmount.length-1))

You could use reduce function to get the desired result.

let amountArray = ["200","150","500","100"];
    let currencyArray = ["EUR","EUR","USD","USD"];
    let result = currencyArray.reduce((acc,c,i) => {
        if(acc.hasOwnProperty(c)){
            return{
                ...acc,
                [c]:parseInt(acc[c])+parseInt(amountArray[i])
            }
        }else{
            return{
                ...acc,
                [c]:amountArray[i]
            }
        }
    },{})
    console.log(result)

If possible, you can creat a class that contains 2 fields, 1 is amount, 1 is corresponding currency. Then you can group by currency and then do the sum up

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

var result =  amountArray.reduce(function(result, field, index) {
//console.log(field);
  if(!(currencyArray[index] in result)){
  //console.log("afaff");
  result[currencyArray[index]] = 0;
  }
  result[currencyArray[index]] =  result[currencyArray[index]] + parseInt(field);
  //console.log(result)
  return result;
}, {})


console.log(totalAmount);
//totalAmount = "350 EUR | 600 USD";

Use forEach to go over both arrays and build one object with accumulated values. Then use map and join to make required string.

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

const res = {};
currencyArray.forEach(
  (key, i) => (res[key] = (res[key] ?? 0) + Number(amountArray[i]))
);
const str = Object.entries(res)
  .map(([key, sum]) => `${sum} ${key}`)
  .join(" | ");

console.log(str);

A hashmap solution. The first part forms the hashmap which uses currency as key and amount array as value. The second part constructs the string result. The time complexity is O(n^2), space complexity is O(n). n is the length of amountArray or currencyArray.

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

function getTotalAmount() {
  // --- First Part ---- //
  const map = new Map()
  const uniqueCurrencyArray = [];
  for (let i = 0; i < currencyArray.length; i++) {
    if (!uniqueCurrencyArray.includes(currencyArray[i])) {
      uniqueCurrencyArray.push(currencyArray[i]);
    }
  }
  for(const currency of uniqueCurrencyArray) {
    const result = []
    for(const [index, cur] of currencyArray.entries()) {
      if(cur === currency) {
        result.push(amountArray[index])
      }
    }
    map.set(currency, result)
  }
  // --- Second Part -- //
  let finalResult = ""
  for(const key of map.keys()) {
    if(finalResult !== "") {
      finalResult += " | "
    }
    const amountArr = map.get(key)
    let totalAmount = 0
    for(const amount of amountArr) {
      totalAmount += parseInt(amount, 10)
    }
    finalResult += `${totalAmount} ${key}`
  }
  return finalResult
}

console.log(getTotalAmount())

I have used java to solve this..

        String[] amountArray = {"200","150","500","100"};
        String[] currencyArray = {"EUR","EUR","USD","USD"};
        HashMap<String, Integer> map = new HashMap<>();

        for(int i =0; i < currencyArray.length;i++)
        {
            Integer n = Integer.parseInt(amountArray[i]);
            Integer old = map.get(currencyArray[i]);
            if(old == null)
            {
                old = new Integer(0);
            }
            Integer val = n+old;
            map.put(currencyArray[i], val);
        }
Related