JavaScript映射然后过滤唯一的数组项

Ste*_*eve 6 javascript arrays es6-map

我知道如何分别做这两个事情,但是我确信必须有一种将它们组合在一起的方法。

我有一组类别,这些类别是从一组对象中提取的:

 this.videoCategories = this.videos.map(v => v.category);
Run Code Online (Sandbox Code Playgroud)

但是,当然,此数组中有重复项。所以现在我做了

this.uniqueVideoCategories = this.videoCategories.filter((item, index) => {
  return this.videoCategories.indexOf(item) === index;
});
Run Code Online (Sandbox Code Playgroud)

效果很好,我得到了一系列没有重复的类别。但是我试图通过将它们串在一起来学习和弄清代码,但这不起作用-产生空数组

  constructor(private videoService: VideoService) {
    this.videos = videoService.getVideos();
    this.videoCategories = this.videos
      .map(v => v.category)
      .filter((item, index) => {
        return this.videoCategories.indexOf(item) === index;
      });
    console.log(this.videoCategories);
  }
Run Code Online (Sandbox Code Playgroud)

Mah*_*Ali 5

在内部,filter()您正在检查对象数组内的索引。您可以使用方法的第三个参数filter(),它将是之后新创建的数组map()

 constructor(private videoService: VideoService) {
    this.videos = videoService.getVideos();
    this.videoCategories = this.videos
      .map(v => v.category)
      .filter((item, index, arr) => {
        return arr.indexOf(item) === index;
      });
    console.log(this.videoCategories);
  }
Run Code Online (Sandbox Code Playgroud)

您可以使用filter()and来删除重复项,而不是使用。这将是时间复杂度indexOf()SetO(N)

constructor(private videoService: VideoService) {
    this.videos = videoService.getVideos();
    this.videoCategories = [...new Set(this.videos.map(v => v.category))]
    console.log(this.videoCategories);
  }
Run Code Online (Sandbox Code Playgroud)


an_*_*ets 0

数组为空,因为当您过滤数组时return this.videoCategories.indexOf(item) === index;,字段this.videoCategories为空。

尝试一下:

this.videoCategories = this.videos
    .map(v => v.category)
    .filter((item, index, array) => {
        return array.indexOf(item) === index;
    });
Run Code Online (Sandbox Code Playgroud)