如果第二个数组匹配,则从第一个数组求和

时间:2020-06-16 08:26:49

标签: javascript arrays

我有2个看起来像这样的数组:

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

如果第二个数组匹配,我想从第一个数组中求和。 结果我想得到:

totalAmount = "350 EUR | 600 USD";

9 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);

答案 2 :(得分: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))

答案 3 :(得分: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)

答案 4 :(得分:1)

如果可能的话,您可以创建一个包含2个字段的类,1是金额,1是对应的货币。然后您可以按货币分组,然后求和

答案 5 :(得分: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";

答案 6 :(得分: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);

答案 7 :(得分: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())

答案 8 :(得分:0)

我用java解决了这个问题。

 {"off":
  {
    "02":{
      "id":"02"
         },
    "name":"022",
    "type":"Test",
    "phn":[1,2,3,4],
    "org":"wann",
    "email":"cc@gmail.com",
    "description":"AS",
    "html":"<div>ID: 02<br>Name: 022<br>Org: wann<br>Description: AS</div>"
  }
 }
    ####################
 final jsonResponse= json.decode(response.body);