So I have a problem here that I have a list of objects with an ID and time. So what I did here was trying to loop out each of these results and push a number based on the time that I set. It would also push 0 if the time does not equal of the hour.
let formatted = [];
const results = [
{ id: 'id1', time: 4 },
{ id: 'id1', time: 5 },
{ id: 'id2', time: 1 },
{ id: 'id2', time: 15 },
{ id: 'id2', time: 12 },
{ id: 'id3', time: 6 },
{ id: 'id3', time: 8 },
];
const hours = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, ];
results.forEach((result) => {
let hourArr = [];
hours.forEach((hour) => {
hourArr.push(result.time == hour ? hour : 0);
});
formatted.push({ id: result.id, time: hourArr });
});
console.log(formatted);
Output:
[
{
id: 'id1',
time: [
0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
{
id: 'id1',
time: [
0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
{
id: 'id2',
time: [
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
{
id: 'id2',
time: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
{
id: 'id2',
time: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
{
id: 'id3',
time: [
0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
{
id: 'id3',
time: [
0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
];
The problem here is that every iteration of the object only inserts as a new object instead of combining the existing one.
What I want for the output:
[
{
id: 'id1',
time: [
0, 0, 0, 0, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
{
id: 'id2',
time: [
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
{
id: 'id3',
time: [
0, 0, 0, 0, 0, 0, 6, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
],
},
];