我有一个数组
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'},
]
我如何获得此friendList的唯一数组。这样结果是:
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'}
]
如果friendList
项目应由唯一的id
属性过滤,则可以利用对象应该具有唯一键的事实。
考虑到这一点,您可以
Array.prototype.reduce()
遍历源数组并构建一个对象,以id
作为键,并使用相应的项目对象作为值Object.values()
提取到唯一记录数组中>以下是概念现场演示的证明:
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%;}