skip to Main Content

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


  1. Check the below code.

    let arr = [
        { "time": 0 },
        { "endTime": 4.5, "time": 4 },
        { "time": 5 },
        { "endTime": 7, "time": 6 },
        { "endTime": 10, "time": 8 },
        { "endTime": 15, "time": 11 },
    ];
    
    let arrayOfSliderStartEndTime = arr.reduce((pv, cv, i) => {
        if (!("endTime" in cv)) {
            pv.res.push(cv.time);
        } else {
            if (pv.res.length % 2 !== 0) {
                pv.res.push(cv.endTime);
            } else {
                pv.res.push(cv.time, cv.endTime);
            }
        }
        return pv;
    }, { res: [] }).res;
    
    console.log(arrayOfSliderStartEndTime);
    Login or Signup to reply.
  2. An one-liner version:

    const result = arr.reduce((r, {time, endTime}) => (endTime !== undefined ? r.length % 2 ? r.push(endTime) : r.push(time, endTime) : r.push(time), r), []);
    
    console.log(...result);
    <script>
    const arr = [
        {
            "time": 0,
        },
        {
            "endTime": 4.5,
            "time": 4,
        },
        {
            "time": 5,
        },
        {
            "endTime": 7,
            "time": 6,
        },
        {
            "endTime": 10,
            "time": 8,
        },
        {
            "endTime": 15,
            "time": 11,
        },
    ]
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search