i have array data like this
[{
date: "January 2019",
sum: 20,
name: "Persada",
},{
date: "Februay 2019",
sum: 21,
name: "Persada",
},{
date: "April 2019",
sum: 22,
name: "Persada",
},{
date: "January 2019",
sum: 10,
name: "Kharisma",
},{
date: "March 2019",
sum: 5,
name: "Kharisma",
},{
date: "Februari 2019",
sum: 4,
name: "Solusindo",
},{
date: "Mai 2019",
sum: 2,
name: "Solusindo",
}]
From the data above, I have chosen a different date. so I get a date like this
["January 2019", "February 2019", "March 2019", "April 2019", "Mai 2019"]
and then i want to set data like this
[{
date : ["January 2019", "February 2019", "March 2019", "April 2019", "Mai 2019"],
sum: [20, 21, 0, 22, 0],
name: "Persada",
},{
date : ["January 2019", "February 2019", "March 2019", "April 2019", "Mai 2019"],
sum: [0, 0, 10, 5, 0],
name: "Kharisma",
},{
date : ["January 2019", "February 2019", "March 2019", "April 2019", "Mai 2019"],
sum: [0, 4, 0, 0, 2],
name: "Solusindo",
}]
if there is no data on that date, then the data sum will automatically be replaced by 0. please help me to set data like that. thank you
2
Answers
Set
,Array.from
to create an initial entries)Object.entries
to create dictionary form array)Array.prototype.reduce
create a dictionary ofdate and sum
withname
as keyObject.entries
to loop through the dictionary to create the result set.Object.keys
to extractdates
from the date dictionaryObject.values
to extractsum
from the date dictionary1) Build an Object with unique keys as
name
and values of sum, date, name.2) Go over data with
forEach
loop, if the key does not exist then add the default values ofsum
with array of ‘0’s with array size of dates.3) Update the respective
sum
value.4) In the function return the Object values of
res
as an array.