我有两个数组,它们看起来像这样:
amountArray = ["200","150","500","100"];
currencyArray = ["EUR","EUR","USD","USD"];
如果第二个数组匹配,我想对第一个数组中的金额进行求和。
我希望得到的结果是:
totalAmount = "350 EUR | 600 USD";
我有两个数组,它们看起来像这样:
amountArray = ["200","150","500","100"];
currencyArray = ["EUR","EUR","USD","USD"];
如果第二个数组匹配,我想对第一个数组中的金额进行求和。
我希望得到的结果是:
totalAmount = "350 EUR | 600 USD";
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);
使用货币作为键将数据存储在哈希映射中。然后在循环遍历金额时,如果该键存在,则将其添加到现有总和中。
最后,转换回数组并打印。
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);
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))
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)
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";
forEach
遍历两个数组并构建一个累加值的对象。然后使用map
和join
来生成所需的字符串。
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);
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())
我用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);
}