如果数组包含重复项,则将两个值合并为一个
if array contains duplicate, merge both values as one
我有一个数组,如下所示:
有没有一种方法可以在将另一个对象“AAPL”添加到数组时添加费用和金额,而 AAPL 在数组中保留一个对象?
提前致谢!
首先确定条目,然后将另一个整数添加到该值。
这取决于您现在如何更新该对象 - 如果它始终处于 0 位置,则只需 portfolioHoldings[0][amount] += number;
如果不是,则遍历所有并检查是否 ticker_symbol == AAPL,然后通过添加所需的数量来更新该数组值。
我不想假设“AAPL”总是在数组中。
首先检查新项是否在数组中。如果没有,我将 return 并结束通话(但您可能希望将其附加到数组中,因为它是一个新项目)。
如果是,替换当前对象(或对象的一部分,在这种情况下我只做了费用和金额)
function addPortfolioItem(item) {
const index = returnPortfolioHoldingIndex(item);
if (index = -1) {
// Returning if not found - You may wish to append to the array as mentioned above
return;
} else {
// Overwrite the object within the array with the new object
portfolioHoldings[index].fees = item.fees;
portfolioHoldings[index].amount = item.amount;
}
}
function returnPortfolioHoldingIndex() {
const tickerSymbolToSearch = "AAPL";
return portfolioHoldings.findIndex(item => item.ticker_symbol === tickerSymbolToSearch);
}
我有一个数组,如下所示:
有没有一种方法可以在将另一个对象“AAPL”添加到数组时添加费用和金额,而 AAPL 在数组中保留一个对象?
提前致谢!
首先确定条目,然后将另一个整数添加到该值。
这取决于您现在如何更新该对象 - 如果它始终处于 0 位置,则只需 portfolioHoldings[0][amount] += number;
如果不是,则遍历所有并检查是否 ticker_symbol == AAPL,然后通过添加所需的数量来更新该数组值。
我不想假设“AAPL”总是在数组中。
首先检查新项是否在数组中。如果没有,我将 return 并结束通话(但您可能希望将其附加到数组中,因为它是一个新项目)。
如果是,替换当前对象(或对象的一部分,在这种情况下我只做了费用和金额)
function addPortfolioItem(item) {
const index = returnPortfolioHoldingIndex(item);
if (index = -1) {
// Returning if not found - You may wish to append to the array as mentioned above
return;
} else {
// Overwrite the object within the array with the new object
portfolioHoldings[index].fees = item.fees;
portfolioHoldings[index].amount = item.amount;
}
}
function returnPortfolioHoldingIndex() {
const tickerSymbolToSearch = "AAPL";
return portfolioHoldings.findIndex(item => item.ticker_symbol === tickerSymbolToSearch);
}