Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to loop and group value by checking whether key present or not in array of object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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)
        }

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading