Remove original and duplicate from an array of objects - JS

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

    That's a one-liner:

    list.filter(el => list.filter(e => e.title == el.title).length == 1);
    

    const arr = [{
        title: "sky",
        artist: "Jon",
        id: 1
      },
      {
        title: "rain",
        artist: "Paul",
        id: 2
      },
      {
        title: "sky",
        artist: "Jon",
        id: 1
      }
    ];
    
    const arr1 = [{
        title: "sky",
        artist: "Jon",
        id: 1
      },
      {
        title: "rain",
        artist: "Paul",
        id: 2
      },
      {
        title: "sky",
        artist: "Jon",
        id: 1
      },
      {
        title: "rain",
        artist: "Paul",
        id: 2
      }
    ];
    
    
    function removeDupes(list) {
      return list.filter(el => list.filter(e => e.id == el.id).length == 1);
    }
    
    console.log(removeDupes(arr));
    console.log(removeDupes(arr1));

提交回复
热议问题