来自JavaScript中具有相似键的数组值的总和
假设,这是一个数组,其中包含一些公司在一段时间内买卖的股票的一些数据。
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 ]
}