The original array has several objects within it, each of these objects has three properties (timestamp, name and age).
If multiple timestamps in a row are 15 minutes apart, they will be grouped into the same object. Afterwards, a new property called end will be added, which will be the timestamp value of the last element of this group plus 15 minutes.
If there are not several elements in a row with a difference of 15 minutes between them, the end property will have the timestamp plus 15 minutes as a value.
This is my current code:
const data = [
{
timestamp: '2021-11-23T14:15:00+0000',
name: 'John',
age: 25,
},
{
timestamp: '2021-11-23T14:30:00+0000',
name: 'John',
age: 25,
},
{
timestamp: '2021-11-23T14:45:00+0000',
name: 'John',
age: 25,
},
{
timestamp: '2021-11-23T15:45:00+0000',
name: 'John',
age: 25,
},
{
timestamp: '2021-11-23T14:15:00+0000',
name: 'Anne',
age: 32,
},
{
timestamp: '2021-11-23T14:30:00+0000',
name: 'Anne',
age: 32,
},
{
timestamp: '2021-11-23T14:45:00+0000',
name: 'Anne',
age: 32,
},
{
timestamp: '2021-11-23T15:45:00+0000',
name: 'Anne',
age: 32,
},
]
const newArray = data.reduce((accumulator, current) => {
const end = new Date(Date.parse(current.timestamp) + 15 * 60 * 1000)
if (accumulator.length === 0) {
accumulator.push({
...current,
end,
})
} else {
const last = accumulator[accumulator.length - 1]
if (last.name === current.name && last.age === current.age) {
last.end = end
} else {
accumulator.push({
...current,
end,
})
}
}
return accumulator
}, [])
console.log(newArray)
However the end result of my code is not exactly what I want. I would like my result to be like this:
[
{
timestamp: '2021-11-23T14:15:00+0000',
name: 'John',
age: 25,
end: '2021-11-23T15:00:00+0000'
},
{
timestamp: '2021-11-23T15:45:00+0000',
name: 'John',
age: 25,
end: '2021-11-23T16:00:00+0000'
},
{
timestamp: '2021-11-23T14:15:00+0000',
name: 'Anne',
age: 32,
end: '2021-11-23T15:00:00+0000'
},
{
timestamp: '2021-11-23T15:45:00+0000',
name: 'Anne',
age: 32,
end: '2021-11-23T16:00:00+0000'
}
]
{}and the original array has 8 objects{}...why?