Published Sep 28 2018
Suppose you have a bills array with this content:
const bills = [
{ date: '2018-01-20', amount: '220', category: 'Electricity' },
{ date: '2018-01-20', amount: '20', category: 'Gas' },
{ date: '2018-02-20', amount: '120', category: 'Electricity' }
]
and you want to extract the unique values of the category
attribute of each item in the array.
Hereβs what you can do:
const categories = [...new Set(bills.map(bill => bill.category))]
Set is a new data structure that JavaScript got in ES6. Itβs a collection of unique values. We put into that the list of property values we get from using map()
, which how we used it will return this array:
['Electricity', 'Gas', 'Electricity']
Passing through Set, weβll remove the duplicates.
...
is the spread operator, which will expand the set values into an array.
I wrote an entire book on this topic π
I also got a super cool course π
© 2023 Flavio Copes
using
Notion to Site
Interested in solopreneurship?