簡體   English   中英

Javascript map然后過濾唯一的數組項

[英]Javascript map then filter unique array items

我知道如何分別做兩件事,但我確信必須有辦法將它們結合起來。

我有一個類別數組,我從一個對象數組中提取:

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

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

您可以使用Set刪除重復項,而不是使用filter()indexOf() 這將是時間復雜度O(N)

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

 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 :(可選)執行回調時用作此值的值。

返回值

包含通過測試的元素的新數組。 如果沒有元素通過測試,則返回一個空數組。

有時,解決方案是選擇正確的數據結構。 ES6引入了Set ,它只包含唯一的對象。

那你就做:

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

唯一性將由瀏覽器實現處理,而不是混亂您的代碼庫。

數組為空,因為當你進行過濾數組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;
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM