6

我知道如何分别做这两件事,但我确信必须有一种方法可以将它们结合起来。

我有一个类别数组,我从一组对象中提取:

 this.videoCategories = this.videos.map(v => v.category);

但当然,这个数组中有重复项。所以现在我做

this.uniqueVideoCategories = this.videoCategories.filter((item, index) => {
  return this.videoCategories.indexOf(item) === index;
});

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

  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);
  }
4

4 回答 4

4

在内部,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);
  }

而不是使用filter()andindexOf()您可以使用Set来删除重复项。这将是时间复杂度O(N)

constructor(private videoService: VideoService) {
    this.videos = videoService.getVideos();
    this.videoCategories = [...new Set(this.videos.map(v => v.category))]
    console.log(this.videoCategories);
  }
于 2019-08-01T15:07:44.903 回答
1

var videos = [
  { category: 'category1', title: 'Category 1'},
  { category: 'category1', title: 'Category 1'},
  { category: 'category1', title: 'Category 1'},
  { category: 'category2', title: 'Category 2'},
  { category: 'category2', title: 'Category 2'}
];
var categoryVideos =
  videos
    .map(v => v.category)
    .filter((item, index, arr) => arr.indexOf(item) === index);
    
console.log(categoryVideos);

Array.prototype.filter

句法

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

参数

打回来

函数是一个谓词,用来测试数组的每个元素。返回 true 以保留元素,否则返回 false。它接受三个参数:

  • element:数组中正在处理的当前元素。
  • index:(可选)数组中正在处理的当前元素的索引。
  • array:(可选)调用了数组过滤器。
  • thisArg:(可选)执行回调时用作 this 的值。

返回值

包含通过测试的元素的新数组。如果没有元素通过测试,将返回一个空数组。

于 2019-08-01T15:08:06.257 回答
1

有时解决方案是选择正确的数据结构。ES6 引入了Set,它只包含唯一的对象。

然后,您只需执行以下操作:

this.videoCategories = new Set(this.videos.map(v => v.category))

唯一性将由浏览器实现处理,而不是弄乱你的代码库。

于 2019-08-01T15:10:19.593 回答
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;
    });
于 2019-08-01T15:13:50.090 回答