Get Unique values from an object or array
Today I will discuss how to get unique value from an object or array in Javascript. This unique value is widely using in many places like menu category, seperate some unique items.
First make an array named is menu with two values object(name and category)
Workflow
Get all instances using map() from the menu array
This map() function loop over the array and get the all instance
Output is
(8) [‘breakfast’, ‘lunch’, ‘dinner’, ‘breakfast’, ‘breakfast’, ‘dinner’, ‘lunch’, ‘breakfast’]
We will use set object to get the unique value.
Set object lets you get or store the unique values of any types.
For more about set object please read set in Javasript
Output is
Set(3) {‘breakfast’, ‘lunch’, ‘dinner’}
Every this good but the problem the set object gives us an object. We need as array. How can I get it? The easy solution is use spread operator. The spread operator returns it as array. [More about spread operator please read] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
Output is
(4) [‘all’, ‘breakfast’, ‘lunch’, ‘dinner’]
This is how we can get the unique value from an object or array. This is super useful in real life.
:) Happy coding