I have some data that needs to be transformed into one array, one by one.
This is the example data (there can be a lot more squads):
var my_arr = [];
var squad1 = [
{ date: "2022-04-04", number_of_checkable_cells: 2 },
{ date: "2022-04-05", number_of_checkable_cells: 2 }
];
var squad2 = [
{ date: "2022-04-04", number_of_checkable_cells: 2 },
{ date: "2022-04-05", number_of_checkable_cells: 1 },
{ date: "2022-04-06", number_of_checkable_cells: 2 }
];
What happens: my_arr receives squad1 to add it, later squad2 joins the party.
So after squad1 is added my_arr should be:
my_arr = [
{ date: "2022-04-04", number_of_checkable_cells: 2 },
{ date: "2022-04-05", number_of_checkable_cells: 2 }
];
Then the data of squad2 is received and I want the following result:
my_arr = [
{ date: '2022-04-04', number_of_checkable_cells: 4 },
{ date: '2022-04-05', number_of_checkable_cells: 3 },
{ date: '2022-04-06', number_of_checkable_cells: 2 }
]
The code that I have:
function reduce_it(arr) {
return arr.reduce((initiator, curr) => {
var obj = initiator.find((i) => i.date == curr.date);
if (obj) obj.number_of_checkable_cells += curr.number_of_checkable_cells;
else initiator.push(curr);
return initiator;
}, []);
}
my_arr = [...my_arr, ...squad1];
my_arr = reduce_it(my_arr);
my_arr = [...my_arr, ...squad2];
my_arr = reduce_it(my_arr);
Is there a better way to get to the same result? If there is, please guide me. :)