根据数组中的其他值求和



我有一个表示股票交易的对象数组:

[{
date : ...,
symbol: 'TSLA',
amount: 3,
price: 1000.00
},
{
date : ...,
symbol: 'AAPL',
amount: 1,
price: 1200.00
},
{
date : ...,
symbol: 'AAPL',
amount: 7,
price: 1300.00
}]

我需要得到基于数组符号的金额总和,所以输出将是:

[{
symbol: 'TSLA',
amount: 3,
},
{
symbol: 'AAPL',
amount: 8,
}]

是否有一个有效的方法来做到这一点,在javascript内建的操作,或者是唯一的方法来做它与2数组和双循环?

我正在考虑将符号保存在单独的集合中,然后将所有的数量相加,但是有没有更好的方法?

我已经试过了,但这似乎只复制原始数组。

const checkIfExists = (array, value) => {
array.forEach((el, i) => {
if (el.symbol === value) {
return i;
}
});
return -1;
};
const calculateSameValues = (data) => {
let result = [];
data.forEach((el) => {
const index = checkIfExists(result, el.symbol);
if (index === -1) {
result.push({symbol: el.symbol, amount: el.amount});
} else result[index].amount += el.amount;
});
console.log(result);
};

似乎我的checkIfExists函数总是返回-1。我通过将index保存在单独的变量中并返回它来修复它。

代码:

const checkIfExists = (array, value) => {
let index = -1;
array.forEach((el, i) => {
if (el.symbol === value) {
console.log(i);
index = i;
}
});
return index;
};

注意,这仍然使用2个循环,我在寻找更有效的东西,但这工作。

可以这样使用array.reduce()

const arr = [{
symbol: 'TSLA',
amount: 3,
price: 1000.00
},
{
symbol: 'AAPL',
amount: 1,
price: 1200.00
},
{
symbol: 'AAPL',
amount: 7,
price: 1300.00
}]
const x = arr.reduce(function(acc, cur) {
const idx = acc.findIndex(el => el.symbol === cur.symbol);
const obj = {
symbol: cur.symbol,
amount: cur.amount,
}
if(idx < 0) {
acc.push(obj)
} else {
acc[idx].amount = acc[idx].amount + cur.amount;
}

return acc;
}, []);
console.log(x);

最新更新