0

I have an array of objects and want to keep the objects that have duplicate ID's. So I want to filter out the objects that do not have duplicate ID's. Can any1 help me with this?

//Example
var videos: [{id: 1, name: video1}, {id: 2, name: video2}, {id: 3, name: video3}, {id: 1, name: video1}, {id: 3, name: video3}];

//result
var filteredVideos: [{id: 1, name: video1}, {id: 3, name: video3}];
Baartuh
  • 1
  • 1

2 Answers2

0

In environments that support Set pass a Set to Array#filter() as the this argument

var videos = [{id: 1, name: 'video1'}, {id: 2, name: 'video2'}, {id: 3, name: 'video3'}, {id: 1, name: 'video1'}, {id: 3, name: 'video3'}];

var filteredVideos = videos.filter(function(o) {
   return  !this.has(o.id)  &&  this.add(o.id) 
},new Set)

console.log(filteredVideos)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • This returns me the array without the duplicate values. What I want is to know which objects are in there twice and return them to me. So the end result would be: var filteredVideos: [{id: 1, name: video1}, {id: 3, name: video3}]; – Baartuh Dec 03 '18 at 09:08
-1

var videos =  [{id: 1, name: 'video1'}, {id: 2, name: 'video2'}, {id: 3, name: 'video3'}, {id: 1, name: 'video1'}, {id: 3, name: 'video3'}];
var uniqueVideosById = {},
    filteredVideos = [];
var allVideoIds = videos.map( video => {
    if(!uniqueVideosById[video.id]) {
      uniqueVideosById[video.id] = video;
    } else {
      filteredVideos.push(video)
    }
   return video.id;
})

console.log('filteredVideos: ', filteredVideos);
sridhar
  • 612
  • 5
  • 12