ES6: Using Set For Unique Arrays
In the past, getting unique values meant pulling an external library or creating your own.
Now, you can easily do that with Set and Array.from
.
const books = ['Matilda', 'Charlie and the Chocolate Factory', 'Matilda', 'James and the Giant Peach', 'Matilda']
const uniqueBooks = Array.from(new Set(books))
// => ['Matilda', 'Charlie and the Chocolate Factory', 'James and the Giant Peach']
Set
lets you store unique values and accepts any Object
or primitive to be passed in to it’s initializer.
When the data passed in has multiple items, it strips them out automatically.
Spread Operator
A simpler syntax exists if you use the spread operator:
const books = ['Matilda', 'Charlie and the Chocolate Factory', 'Matilda', 'James and the Giant Peach', 'Matilda']
const uniqueBooks = [...new Set(books)]
No comments yet. Share on Mastodon and see your comment or write a post on your blog if you support Webmentions
No reposts yet. Share on Mastodon and see your repost or write a post on your blog if you support Webmentions
No likes yet. Share on Mastodon and see your like or write a post on your blog if you support Webmentions
No bookmarks yet. Share on Mastodon and see your bookmark or write a post on your blog if you support Webmentions
Powered by Webmentions