How to create an array of unique values using Set?

ES6 introduces Set, which returns unique values

This article will go through how to remove duplicates and create an array of unique values ES6 Set.

What is ES6 Set?

The Set object is a data type that can store unique values without any particular order.

We can pass in a parameter, and all of its elements will be added to the new Set.

const result = new Set(parameter);

How to create an array with unique values?

For example, we want to create a new array with unique category values.

const food = [
  {
    name: "egg",
    category: "breakfast",
  },
  {
    name: "burger",
    category: "lunch",
  },
  {
    name: "steak",
    category: "dinner",
  },
  {
    name: "chicken",
    category: "lunch",
  },
  {
    name: "eggs",
    category: "breakfast",
  },
  {
    name: "spaghetti",
    category: "dinner",
  },
];

Step 1: Use map() to get all instance:

const categories = food.map((item) => item.category);

console.log(categories) // ["breakfast", "lunch", "dinner", "lunch", "breakfast", "dinner"]

Step 2: Use new Set() to get unique values:

const categories = new Set(food.map((item) => item.category));

console.log(categories) // {"breakfast", "lunch", "dinner"}

Step 3: Convert it to an array:

To convert an object into an array, we use the spread operator:

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

console.log(categories) // ["breakfast", "lunch", "dinner"]

Overall

In summary, we can use the following syntax to remove duplicates in an array:

const result = [...new Set(list)];