DEV Community

StuartCreed
StuartCreed

Posted on • Updated on

Removing Duplicate numbers or Objects from an Array

For Numbers

const array = [1,1,2,3,3,4,5,6]

to remove duplicates (as Set only takes unique values):
array = [...new Set(array)]

or

array = array.filter((i, index) => array.indexOf(i) === index)

or

array = array.reduce((accum, item) => {return accum.includes(item) ? accum : [...accum, item]}, [])
Enter fullscreen mode Exit fullscreen mode

For Objects

e.g: If you have an array of objects like:

(5) [{…}, {…}, {…}, {…}, {…}]
0: {geometry: ol.g…m.Polygon, id: 17105, district_id: 20, map_type_id: 117, address: "Site at The Cranhams, Cranhams Lane, Cirencester", …}
1: {geometry: ol.g…m.Polygon, id: 17323, district_id: 20, map_type_id: 127, address: "Chesterton Farm, Tetbury Road Cirencester", …}
2: {geometry: ol.g…m.Polygon, id: 43065, district_id: 20, map_type_id: 116, address: "Land at Chesterton Farm", …}
3: {geometry: ol.g…m.Polygon, id: 49216, district_id: 20, map_type_id: 122, address: "South of Chesterton, Cirencester", …}
4: {geometry: ol.g…m.Polygon, id: 104198, district_id: 20, map_type_id: 127, address: "57 London Road", …}
5: {geometry: ol.g…m.Polygon, id: 104198, district_id: 20, map_type_id: 127, address: "57 London Road", …}
length: 6
__proto__: Array(0)

Enter fullscreen mode Exit fullscreen mode

To remove the duplicate 57 London Road objects, where the array of objects is this.planSitesWithinSite:


        let siteIds = this.planSitesWithinSite.map((site) => site.id)
        siteIds = [...new Set(siteIds)] //Removes duplicate ids
        this.planSitesWithinSite = siteIds.map((siteId) => {
            return this.planSitesWithinSite.find((site) => site.id === siteId)
        })
        lsDebug({lsModule: this, message: "Planning sites within this site after removal of duplicate sites", data: this.planSitesWithinSite});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)