Remove original and duplicate from an array of objects - JS

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

    You can group the items by id, and then use _.flatMap() to convert back a single array. In the _.flatMap() callback return an empty array if the group has more than one item:

    const fn = arr => _.flatMap(
      _.groupBy(arr, 'id'), // group by the id
      group => _.size(group) > 1 ? [] : group // check the size and return an empty array for groups with more than a single item
    )
    
    const arr1 = [{"title":"sky","artist":"Jon","id":1},{"title":"rain","artist":"Paul","id":2},{"title":"sky","artist":"Jon","id":1}]
    const arr2 = [{"title":"sky","artist":"Jon","id":1},{"title":"rain","artist":"Paul","id":2},{"title":"sky","artist":"Jon","id":1},{"title":"rain","artist":"Paul","id":2}]
    
    console.log(fn(arr1))
    console.log(fn(arr2))

    Another example

提交回复
热议问题