Remove original and duplicate from an array of objects - JS

前端 未结 8 1422
时光取名叫无心
时光取名叫无心 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:57

    You could take an object and filter with the value of the hash table.

    const
        array = [{ title: "sky", artist: "Jon", id: 1 }, { title: "rain", artist: "Paul", id: 2 }, { title: "sky", artist: "Jon", id: 1 }, { title: "rain", artist: "Paul", id: 2 }],
        ids = array.reduce((r, { id }) => (r[id] = !(id in r), r), {}),
        result = array.filter(({ id }) => ids[id]);
    
    console.log(result);

提交回复
热议问题