Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out unique value from object inside array using loadsh

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


2 Answers

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/

like image 192
tymeJV Avatar answered Feb 25 '26 10:02

tymeJV


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.)

like image 40
Naftali Avatar answered Feb 25 '26 09:02

Naftali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!