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

Grouping a dynamic array object and forming a object required

I have a dynamic object something like this

var object = [
    "70669",
    "70669|9436",
    "70669|8353",
    "70669|8914",
    "70669|9522",
    "70669|8422",
    "70669|9639"
    ]

My expected output is something like this

[{
    stdSizeCode: [9436, 8353, 8914, 9522, 8422, 9639]
    productHierSk: 70669
}]

I have tried to looking into this link and did not work the way that is expected. Can someone please suggest

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

>Solution :

You could group by with an object and get the values as result.

const
    data = ["70669", "70669|9436", "70669|8353", "70669|8914", "70669|9522", "70669|8422", "70669|9639"],
    result = Object.values(data.reduce((r, s) => {
        const [productHierSk, code] = s.split('|').map(Number);
        r[productHierSk] ??= { stdSizeCode: [], productHierSk };
        if (value !== undefined) r[productHierSk].stdSizeCode.push(code);
        return r;
    }, []));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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