Update an array with dates and value to include missing dates

Viewed 123

I have 2 arrays with the following data

Array 1 has 8 elements, may vary, never more than 30 elements
I copy pasted these values from my browser console, thought that would be most readable.

Array1
0: {date_usage: "2021-01-28 00:05:28", receipts: 3}
1: {date_usage: "2021-02-01 00:05:28", receipts: 4}
2: {date_usage: "2021-02-02 00:05:28", receipts: 8}
3: {date_usage: "2021-02-05 15:05:16", receipts: 4}
4: {date_usage: "2021-02-09 15:05:17", receipts: 13}
5: {date_usage: "2021-02-10 11:12:10", receipts: 1}
6: {date_usage: "2021-02-18 00:05:29", receipts: 5}
7: {date_usage: "2021-02-19 15:05:18", receipts: 3}

Array 2 has 30 elements.
It is an array with the dates of last 30 days.
All 'receipts' are 0 and all times may vary.

Array2
0: {date_usage: "2021-01-21 00:00:00", receipts: 0}
1: {date_usage: "2021-01-22 14:00:00", receipts: 0}
2: {date_usage: "2021-01-23 09:00:00", receipts: 0}
3: {date_usage: "2021-01-24 10:00:00", receipts: 0}
..............etc
29: {date_usage: "2021-02-21 00:00:00", receipts: 0}

I would like to add the missing dates to Array 1 with JavaScript or create a new array containing this data.
The times don't need to match, only the dates.
Each date will only appear once in both arrays. I know it's a simple question, and many variants of it exist on this forum.
But every time I try a solution I get stuck, so I hope someone can help and point me in the right direction.
If something is unclear, let me know and I'll elaborate further.

3 Answers
for (let i = 0; i < array2.length; i++) {
    if (!array1.includes(array2[i])) {
        array1.push(array2[i])
    }
}

Try this

If I understood correctly, you want to merge the two arrays and as a result have the data ordered by the date.

One way of doing it is just order the (array1+array2) recursively. Another way is appending to the first array one by one in a for loop.

So I ended up with this.

       //get the dates in array1, the first part (yyyy-mm-dd)
       var arr1_dates = array1.map(function(item) {
            return item.date_usage.split(" ")[0];
        });

        //Compare array1 dates with array2 dates &
        //Add missing to array1    
        for (let i = 0; i < array2.length; i++) {
            var date = array2[i].date_closed.split(" ")[0];

            if (!arr1_dates.includes(date)) {
                array1.push(array2[i])
            }
        }

        //Sort the array by date
        array1 = array1.sort(function(a, b) {
            return new Date(b.date_usage) - new Date(a.date_usage);

        });
Related