Filter unique value from object inside array using loadsh

I am trying to get a 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 result like,

VIP PASS and WIP

+3


source to share


3 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/

+4


source


You need to use uniqBy

as uniq

it 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 only want lines (as per the comments) you can simply:

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

+3


source


Solution using Map

and reduce

.

var arr = [{
  "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
}];

var unique = arr.reduce((map, o) => (map.has(o.category) ? map : map.set(o.category)),new Map());
console.log(Array.from(unique.keys()));
      

Run codeHide result


0


source







All Articles