-3

i have an array

friendList = [
              {id: 1, fName: 'Sam', lName: 'Brian', profilePic: 'sam.jpg'},
              {id: 2, fName: 'Dam', lName: 'Nary', profilePic: 'dam.jpg'},
              {id: 3, fName: 'Jam', lName: 'kent', profilePic: 'jam.jpg'},
              {id: 1, fName: 'Sam', lName: 'Brian', profilePic: 'sam.jpg'},
              {id: 3, fName: 'Jam', lName: 'kent', profilePic: 'jam.jpg'}, 
             ]

how can i get a unique array of this friendList.. such that the result is :

friendList = [
              {id: 1, fName: 'Sam', lName: 'Brian', profilePic: 'sam.jpg'},
              {id: 2, fName: 'Dam', lName: 'Nary', profilePic: 'dam.jpg'},
              {id: 3, fName: 'Jam', lName: 'kent', profilePic: 'jam.jpg'}
             ]
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Shubham Shaw
  • 841
  • 1
  • 11
  • 24
  • [No, they are not](https://stackoverflow.com/questions/18773778/create-array-of-unique-objects-by-property). – Daedalus Jun 03 '20 at 08:37
  • var uniqueArry = Object.values(friendList.reduce((acc,ele)=>{return {...acc,...{[ele.id]:ele}}},{})) – Ajai Jun 03 '20 at 09:05

1 Answers1

0

If your friendList items should be filtered by unique id property, you can make use of the fact that object should have unique keys.

With that in mind, you may

  • traverse your source array using Array.prototype.reduce() and build up an object, having id as a key and corresponding item object as a value
  • extract Object.values() into array of unique records

Following is a proof of a concept live-demo:

const friendList = [{id:1,fName:'Sam',lName:'Brian',profilePic:'sam.jpg'},{id:2,fName:'Dam',lName:'Nary',profilePic:'dam.jpg'},{id:3,fName:'Jam',lName:'kent',profilePic:'jam.jpg'},{id:1,fName:'Sam',lName:'Brian',profilePic:'sam.jpg'},{id:3,fName:'Jam',lName:'kent',profilePic:'jam.jpg'},],
             
      friendListMap = friendList.reduce((r,item) => 
        (r[item.id] = item, r), {}),
        
      dedupeFriendList = Object.values(friendListMap)
      
console.log(dedupeFriendList)
.as-console-wrapper{min-height:100%;}
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42