On the click of a button the data in fruitData array gets added to another array called history. I want the property 'bins' inside history to update whenever the properties: "kultivar", "blokNommer" and "year" match with the objects added from fruitData. (number inside bins property needs to be added together if there is a match)
for example this:
[
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"},
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "20", year: "2020"}
]
should equal this (bins: 40):
[
{datum: "2020-04-08", kultivar: "bc", ha: "5", blokNommer: "1", bins: "40", year: "2020"}
]
My code:
let 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"
}
]
historyButton.addEventListener('click', () => {
addToHistory(fruitData)
})
function addToHistory(elements) {
for (let elem in elements) {
history = [...history, elements[elem]];
}
sortHistory()
}
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) {
item.bins = item.bins + itm.bins
} else {
newHistory.push(item)
}
})
}
})
console.log(newHistory)
}
This does not give the output I am looking for. Have tried reduce method as well with no luck. Would appreciate any help!
You need to iterate the original array, and use
find()
to retrieve the existing item in thehistory
array which match tokultivar
,blokNommer
andyear
in order to accessbins
and update it.Note: It's also important to convert
bins
byNumber()
as its string in your example, and after that convert it back tostring
.find() Number()