使用 JS new Set() 過濾重複元素

new Set

  • 是 JavaScript 中的一種物件,用於儲存唯一值。

  • 使用 Set 建構函數將產生的陣列轉換為一個集合 (set)。集合是 JavaScript 的內建資料結構,它可以自動過濾重複的元素。

範例程式碼

const menu = [{
    name: 'pancakes',
    category: 'breakfast',
  },
  {
    name: 'burger',
    category: 'lunch',
  },
  {
    name: 'steak',
    category: 'dinner',
  },
  {
    name: 'bacon',
    category: 'breakfast',
  },
  {
    name: 'eggs',
    category: 'breakfast',
  },
  {
    name: 'pasta',
    category: 'dinner',
  },
];

const categories = [...new Set(menu.map(item => item.category))]

解釋語法

  1. For loop each item with map

    const categories = menu.map(item => item.category)
    
    // (6) ['breakfast', 'lunch', 'dinner', 'breakfast', 'breakfast', 'dinner']
    
  2. Return unique value with new Set

    const categories = new Set(menu.map(item => item.category))
    
    // Set(3) {'breakfast', 'lunch', 'dinner'}
    
  3. Convert to Array using [...]

    const categories = [...new Set(menu.map(item => item.category))]
    
    /* ['breakfast', 'lunch', 'dinner'] */
    
  4. 補充:再多加一個分類

    const newCategories = ['all', ...new Set(menu.map(item => item.category))]
    
    // ['all', 'breakfast', 'lunch', 'dinner']
    
1個讚