按重复ID排序对象数组

时间:2018-11-30 16:12:37

标签: javascript arrays object filter

我有一个对象数组,想要保留具有重复ID的对象。所以我想过滤掉没有重复ID的对象。有人可以帮我吗?

//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}];

2 个答案:

答案 0 :(得分:0)

在支持Set的环境中,将Set传递为Array#filter()作为this参数

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)

答案 1 :(得分:-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);