3 回答

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
您需要迭代原始數(shù)組,并使用檢索數(shù)組中與 , 匹配的find()現(xiàn)有項(xiàng)目,以便訪問和更新它。historykultivarblokNommeryearbins
注意:在示例中將binsby轉(zhuǎn)換為其字符串也很重要,然后將其轉(zhuǎn)換回.Number()string
const arr = [
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"},
{datum: "2020-09-18", kultivar: "wb", ha: "5", blokNommer: "1", bins: "5", year: "2020"},
{datum: "2020-03-09", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"},
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"}
]
const history = [];
arr.forEach(item => {
const found = history.find(({ kultivar, blokNommer, year }) =>
kultivar === item.kultivar && blokNommer === item.blokNommer && year === item.year)
if(found) {
found.bins = (Number(found.bins) + Number(item.bins)).toString();
} else {
history.push(item);
}
});
console.log(history);

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果您的fruitData數(shù)組不是很大,您可以嘗試使用迭代元素并搜索indexOf整個(gè)數(shù)組,將其轉(zhuǎn)換為字符串JSON.stringify
但如果數(shù)組很大,則代碼不是最佳的
const fruitData = [
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"},
{datum: "2020-09-18", kultivar: "wb", ha: "5", blokNommer: "1", bins: "5", year: "2020"},
{datum: "2020-03-09", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"},
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"}]
const sortHistory = (myArray) => Object.keys(myArray).reduce((accum, item) => {
const currItem = JSON.stringify(myArray[item])
const allArr = JSON.stringify(accum)
return (allArr.indexOf(currItem) >= 0) ? accum : accum.concat(myArray[item])
}, [])
console.log(sortHistory(fruitData))

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的實(shí)施的問題是您正在更改itm.bins. Array.forEach 在遍歷每個(gè)元素時(shí)創(chuàng)建每個(gè)元素的副本,因此您更改的任何值都itm不會(huì)反映在實(shí)際數(shù)組中。idx因此,如果您想更改實(shí)際元素,則會(huì)向您提供。
另外,您用于+添加字符串,而不是整數(shù)。您需要先將其轉(zhuǎn)換為整數(shù)才能獲得所需的結(jié)果。
最終代碼應(yīng)該是:
function sortHistory(){
let newHistory = [];
history.forEach(function(item, index){
if(newHistory.length === 0){
newHistory.push(item)
} else{
newHistory.forEach(function(itm, idx){
if(item.year === itm.year && item.kultivar === itm.kultivar && item.blokNommer ===
itm.blokNommer){
newHistory[idx].bins = parseInt(item.bins) + parseInt(itm.bins);
}else{
newHistory.push(item)
}
})
}
})
console.log(newHistory);
history = newHistory;}
- 3 回答
- 0 關(guān)注
- 194 瀏覽
添加回答
舉報(bào)