Set Unique Value in JavaScript with set() Constructor - 04

If we want to get unique values from an array, then we can use a set constructor/object.

let animals = [
    {
      name: "Lion",
      category: "carnivore",
    },
    {
      name: "dog",
      category: "pet",
    },
    {
      name: "cat",
      category: "pet",
    },
    {
      name: "wolf",
      category: "carnivore",
    },
  ];

When we loop through the array, we get repeated values:

let category = animals.map(animal => animal.category); console.log(category); // ["carnivore", "pet", "pet", "carnivore"]

we can get unique values by setting up a condition to avoid repetition. It is a little bit tricky until I came across the set() constructor/object provided by ES6.

Let’s see how we can implement this easily.

// wrap your iteration in the set method like this, and we also have to spread the values into an array.
let category = [...new set(animals.map(animal => animal.category))];
  console.log(category);
  // ["carnivore", "pet"]


Post a Comment

Previous Post Next Post