I have data like below
[
{
"time": 0,
},
{
"endTime": 4.5,
"time": 4,
},
{
"time": 5,
},
{
"endTime": 7,
"time": 6,
},
{
"endTime": 10,
"time": 8,
},
{
"endTime": 15,
"time": 11,
},
]
some have time
only and some have time and endTime
both
the output expecting was:
result : [0, 4.5, 5, 7, 8, 10, 11, 15]
i.e
- if only
time
there it should be pushed to odd index in array i.e 0 and 5 - if it has
time and endTime
and last result array length is odd, endTime should be pushed i.e 4.5 and 7 - if last result length is even and object have both time and endTime then both values should be added in order i.e time=8 and then endTime=10, 11 and then 15 must be pushed to array.
I tried something like below not working
let arrayOfSliderStartEndTime = arr.reduce((pv, cv, i) => {
if(!("endTime" in cv)) pv.res.push(cv.time)
else if("endTime" in cv) {
if(pv.res.length%2 != 0) pv.res.push(cv.time)
pv.res.push(cv.endTime)
}
2
Answers
Check the below code.
An one-liner version: