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

Combine data and find duplicates based on a search value

I have an object as follows:

const overall = {
    mainData: {
        id: 1,
        group: 'grp0'
    },
    data: [
        {
            id: 2,
            group: 'grp3'
        },
        {
            id: 3,
            group: 'grp3'
        }
    ]
}

I want to do a combined check across both mainData and data.

Search for a particular grp in a them. For example searching for grp3.

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 there is at least 2 grp3, return true, else return false.

In the above, result will be true cos there is 2 grp 3.

Another example where it will be true. two grp3.

const overall = {
    mainData: {
        id: 1,
        group: 'grp3'
    },
    data: [
        {
            id: 2,
            group: 'grp3'
        }
    ]
}

An example where it will be false. Only 1 grp3

const overall = {
    mainData: {
        id: 1,
        group: 'grp0'
    },
    data: [
        {
            id: 1,
            group: 'grp1'
        },
        {
            id: 2,
            group: 'grp2'
        },
        {
            id: 3,
            group: 'grp3'
        },
        {
            id: 4,
            group: 'grp4'
        }
    ]
}

How could I achieve this in a single flow of filters and maps?

Currently performing this which feels verbose.

const mainGroup = [overall.mainData];
const dataGroups = overall.data.filter(d => d.group);
const allGroups = [...mainGroup, ...dataGroups];
const isMorethanOneItem = allGroups.filter(item => item.group === 'grp3').length > 1;

>Solution :

Basedon your code, we can reduce it to one line

let contains = [overall.mainData,...overall.data].filter(d => d.group == key).length > 1
const overall = {
    mainData: {
        id: 1,
        group: 'grp0'
    },
    data: [
        {
            id: 2,
            group: 'grp3'
        },
        {
            id: 3,
            group: 'grp3'
        }
    ]
}

let key ='grp3'
let result = [overall.mainData,...overall.data].filter(d => d.group == key).length > 1
console.log(result)
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