从第一个数组中汇总数字,如果第二个数组匹配

4

我有两个数组,它们看起来像这样:

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

如果第二个数组匹配,我想对第一个数组中的金额进行求和。

我希望得到的结果是:

totalAmount = "350 EUR | 600 USD";

1
你有没有考虑过制作一个以货币为键、以金额数组为值的哈希表?然后进行总金额检查? - yue you
11
你有尝试过什么吗? - zb22
1
我认为你不应该像这样分别存储东西。如果你有很多值,这将变得非常混乱。相反,应该将它们存储在一个对象中。 - Red Baron
实际上,我是从一个字符串中获取了所有这些数据,它看起来像这样:"200欧元,150欧元,500美元,100美元"。然后我使用分割和切片来创建这些数组。之后我不知道如何从这些数组中进行求和。 - Kapilnemo
1
每个人都有不同的方法来实现这个。投票给他们哪个代码片段运行。 - Avinash Dalvi
9个回答

6
你可以使用 Map 收集相同货币并获取它们的总和。

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


2

使用货币作为键将数据存储在哈希映射中。然后在循环遍历金额时,如果该键存在,则将其添加到现有总和中。

最后,转换回数组并打印。

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


1
你可以做到这一点。

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))


1
你可以使用reduce函数来获得所需的结果。

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)


1
如果可能的话,您可以创建一个包含两个字段的类,一个是金额,一个是相应的货币。然后您可以按货币分组,然后进行总计。

1

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


1
使用forEach遍历两个数组并构建一个累加值的对象。然后使用mapjoin来生成所需的字符串。

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


0
一个哈希表的解决方案。第一部分构建了一个哈希表,使用货币作为键,金额数组作为值。第二部分构造字符串结果。时间复杂度为O(n^2),空间复杂度为O(n)。n是amountArray或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())

0

我用Java解决了这个问题。

        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);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接