在 JavaScript 中对具有相似键的数组值进行求和
javascriptweb developmentobject oriented programming更新于 2025/10/1 16:12:17
假设,这里有一个数组,其中包含一些公司在一段时间内出售和购买的股票的数据。
const transactions = [ ['AAPL', 'buy', 100], ['WMT', 'sell', 75], ['MCD', 'buy', 125], ['GOOG', 'sell', 10], ['AAPL', 'buy', 100], ['AAPL', 'sell', 100], ['AAPL', 'sell', 20], ['DIS', 'buy', 15], ['MCD', 'buy', 10], ['WMT', 'buy', 50], ['MCD', 'sell', 90] ];
我们想编写一个函数,接收这些数据并返回一个数组对象,该数组的键为股票名称(如‘AAPL’、‘MCD’),值是两个数字的数组,其中第一个元素代表总买入量,第二个元素代表总卖出量。因此,执行此操作的代码将是 −
示例
const transactions = [
['AAPL', 'buy', 100],
['WMT', 'sell', 75],
['MCD', 'buy', 125],
['GOOG', 'sell', 10],
['AAPL', 'buy', 100],
['AAPL', 'sell', 100],
['AAPL', 'sell', 20],
['DIS', 'buy', 15],
['MCD', 'buy', 10],
['WMT', 'buy', 50],
['MCD', 'sell', 90]
];
const digestTransactions = (arr) => {
return arr.reduce((acc, val, ind) => {
const [stock, type, amount] = val;
if(acc[stock]){
const [buy, sell] = acc[stock];
if(type === 'buy'){
acc[stock] = [buy+amount, sell];
}else{
acc[stock] = [buy, sell+amount];
}
}else{
if(type === 'buy'){
acc[stock] = [amount, 0];
}else{
acc[stock] = [0, amount];
}
}
return acc;
}, {});
};
console.log(digestTransactions(transactions));
输出
控制台中的输出将是 −
{
AAPL: [ 200, 120 ],
WMT: [ 50, 75 ],
MCD: [ 135, 90 ],
GOOG: [ 0, 10 ],
DIS: [ 15, 0 ]
}
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

