Remove duplicate objects from an array using javascript

后端 未结 9 1886
野性不改
野性不改 2020-12-02 21:21

I am trying to figure out an efficient way to remove objects that are duplicates from an array and looking for the most efficient answer. I looked around the internet everyt

9条回答
  •  不思量自难忘°
    2020-12-02 21:53

    For those who love ES6 and short stuff, here it's one solution:

    const arr = [
      { title: "sky", artist: "Jon" },
      { title: "rain", artist: "Paul" },
      { title: "sky", artist: "Jon" }
    ];
    
    Array.from(arr.reduce((a, o) => a.set(o.title, o), new Map()).values());
    

    const arr = [
      { title: "sky", artist: "Jon" },
      { title: "rain", artist: "Paul" },
      { title: "sky", artist: "Jon" },
      { title: "rain", artist: "Jon" },
      { title: "cry", artist: "Jon" }
    ];
    
    const unique = Array.from(arr.reduce((a, o) => a.set(o.title, o), new Map()).values());
    
    console.log(`New array length: ${unique.length}`)
    
    console.log(unique)

    The above example only works for a unique title or id. Basically, it creates a new map for songs with duplicate titles.

提交回复
热议问题