I am trying to get the unique category from the following array using loadsh,
[{
"listingId": "p106a904a-b8c6-4d2d-a364-0d21e3505010",
"section": "section1",
"category": "VIP PASS ",
"type": "paper",
"availableTickets": 1
}, {
"listingId": "p106904a-b8c6-4d2d-a364-0d21e3505010",
"section": "section1",
"category": "VIP PASS ",
"type": "paper",
"availableTickets": 2
}, {
"listingId": "pc8f54389-4e58-482a-9535-6917c2948764",
"section": "1",
"category": "WIP",
"type": "paper",
"availableTickets": 1
}]
This is what i have tried
this.categories = _.uniq(this.listings, function (test: ListDAO) { return test.category; });
but the above returns the same array again. how can i get the output result as,
VIP PASS and WIP
Without lodash and using .reduce:
let arr2 = arr.reduce((a, i) => a.indexOf(i.category) > -1 ? a : a.concat(i.category), []);
https://jsfiddle.net/42my6p08/
You need to use uniqBy as uniq only accepts a regular array with no callback for each.
https://lodash.com/docs/4.17.4#uniqBy
You can try this:
this.categories = _.uniqBy(this.listings, ({ category }) => category);
If you want just the strings (as per comments) you can just do:
const getCategory = ({ category }) => category;
this.categories = _.uniqBy(this.listings, getCategory).map(getCategory);
(can also use the same callback function from your OP instead of mine.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With