I have two arrays:
var test = [
["20180115", "0"],
["20180116", "0"],
["20180117", "0"],
["20180118", "0"],
["20180119", "0"],
["20180120", "0"],
["20180121", "0"]]
var test2 = [
["obj1", "20180115", "2"],
["obj2", "20180117", "8"],
["obj3", "20180115", "1"],
["obj4", "20180118", "1"],
["obj5", "20180117", "3"]]
I want to format the test2 array to:
// sum the same day(or same string is ok) value and others add zero
var result = [
["20180115", "3"], // 2+1
["20180116", "0"],
["20180117", "11"], // 8+3
["20180118", "1"], // 1
["20180119", "0"],
["20180120", "0"],
["20180121", "0"]]
This is my current solution:
// sum the same day's data
let sumData = []
test.map(row => {
const foundData = sumData.find(data => data[0] === row[1])
let currentData = []
if (foundData) {
foundData[1] += row[2]
} else {
currentData = [row[1], parseInt(row[2], 10)]
sumData.push(currentData)
}
})
// use test2's date to formate new data
test = test2.map(row => {
const foundData = sumData.find(data => data[0] === row[0])
if (foundData) {
row[1] = parseInt(row[1], 10) + parseInt(foundData[1], 10)
}
return row
})
The code works but I don't think it's a very clean solution. Is there a better or cleaner way of achieving this?