Remove original and duplicate from an array of objects - JS

前端 未结 8 1698
时光取名叫无心
时光取名叫无心 2021-01-28 10:40

I have an array of objects.

const arr = [
  { title: \"sky\", artist: \"Jon\", id: 1 },
  { title: \"rain\", artist: \"Paul\", id: 2 },
  { title: \"sky\", artis         


        
8条回答
  •  不知归路
    2021-01-28 10:51

    you can do it in one line like this:

    const res = arr.filter(elem => (arr.filter(obj => obj.id === elem.id)).length === 1)
    

    or you can do it like this(better in terms of time complexity):

    const arr = [
      { title: "sky", artist: "Jon", id: 1  },
      { title: "rain", artist: "Paul", id: 2  },
      { title: "sky", artist: "Jon", id: 1  },
    
    ];
    
    const counts = arr.reduce((counts, curr) => (counts[curr.id] = ++counts[curr.id] || 1, counts), {})
    const res = arr.filter(curr => counts[curr.id] === 1)
    
    
    

提交回复
热议问题