Search code examples
javascriptduplicatesmap-function

Remove duplicates within the map function


I want to remove duplicates within the map function and I have looked through the different posts on the internet but I am still not finding the solution.

The JSON:

"results": [
    {
        "data": {
            "labels": {
                "results": [
                    {
                        "name": "tom"
                    }
                ]
            }
        }
    },
    {
        "data": {
            "labels": {
                "results": [
                    {
                        "name": "jerry"
                    }
                ]
            }
        }
    },
    {
        "data": {
            "labels": {
                "results": [
                    {
                        "name": "tom"
                    }
                ]
            }
        }
    }
]

The code:

obj.results.map((items) => {
    if (items.data.labels.results.length) {
        items.data.labels.results.map((result) => {
            console.log(result.name);
        });
    }
});

Result

tom

jerry

tom

Expected Result

tom

jerry

Tried this solution but didn't work

obj.results.map((items) => {
    if (items.data.label.results.length) {
        items.data.label.results.map((result) => {
            console.log(Array.from(new Set(result.name)));
        });
    }
});

Result from above code

[ 't', 'o', 'm' ]

[ 'j', 'e', 'r', 'r', 'y' ]

[ 't', 'o', 'm' ]


Solution

  • you can achieve this using flatMap to get all name objects and then map to extract the name field. After that a Set to dedupe. [...new Set(..)] converts the Set back to an array

    const results = [{
        "data": {
            "labels": {
                "results": [{
                    "name": "tom"
                }, {
                    "name": "another name"
                }]
            }
        }
    }, {
        "data": {
            "labels": {
                "results": [{
                    "name": "jerry"
                }]
            }
        }
    }, {
        "data": {
            "labels": {
                "results": [{
                    "name": "tom"
                }]
            }
        }
    }]
    
    const res = [...new Set(results.flatMap(({data:{labels: {results}}}) => results).map(({name}) => name))]
    
    //alternative
    //const res = [...new Set(results.map(({data:{labels: {results}}}) => results).flat().map(({name}) => name))]
    
    console.log(res)