Had my earlier question closed because I left out an important detail.
Say I have the following two Arrays
const salesDates = ['2021/06/30','2021/07/01','2021/07/02','2021/07/03','2021/07/04','2021/07/05','2021/07/06']
and
const jsonSalesData = [
{date: '2021/07/01', company: 'ABC', sales: '32460'},
{date: '2021/07/02', company: 'ABC', sales: '28165'},
{date: '2021/07/03', company: 'ABC', sales: '31546'},
{date: '2021/07/04', company: 'ABC', sales: '12654'},
{date: '2021/07/05', company: 'ABC', sales: '26457'},
{date: '2021/07/06', company: 'ABC', sales: '20351'},
{date: '2021/07/07', company: 'ABC', sales: '56404'},
]
What I need to do is
- Return the objects from
jsonSalesDataif thedateinjsonSalesDatamatches thesalesDatesarray - If there is a date in
salesDatesthat is not injsonSalesDataadd an object to thejsonSalesDatawith thatdateand set thesalesto0.
Desired Output
[
{date: '2021/06/30', company: 'ABC', sales: '0'},
{date: '2021/07/01', company: 'ABC', sales: '32460'},
{date: '2021/07/02', company: 'ABC', sales: '28165'},
{date: '2021/07/03', company: 'ABC', sales: '31546'},
{date: '2021/07/04', company: 'ABC', sales: '12654'},
{date: '2021/07/05', company: 'ABC', sales: '26457'},
{date: '2021/07/06', company: 'ABC', sales: '20351'},
]
notice the addition of the 1st object and the exclusion of the last object
I've tried to use forEach but it only accomplishes #1 (returns the dates in jsonSalesData which match to salesDates). It doesn't add the object if there is no match.
const n = [];
jsonSalesData.forEach(e => {
if (salesDates.includes(e.date)){
n.push(e);
}
})
console.log(n);
I've also tried nested loops, but I can't seem to figure it out. Here's what I did for those:
for (let i = 0; i < jsonSalesData.length; i++){
for (let j = 0; j < salesData.length; j++){
if (jsonSalesData[i].date === salesData[j]){
console.log(jsonSalesData[i].company,jsonSalesData[i].date,jsonSalesData[i].sales)
}
}
}
Same issues with map and filter -- I can't seem to look back at salesData and add an object back to jsonSalesData if something in salesData doesn't exist in jsonSalesData
salesDatesbut not a 2021/06/30 injsonSalesData. Therefore, it was added with a 0 sales.