I know how to do both things separately, but I'm sure there must be a way to combine them.
I have an array of categories, which I am extracting from an array of objects:
this.videoCategories = this.videos.map(v => v.category);
But of course there are duplicates in this array. So now I do
this.uniqueVideoCategories = this.videoCategories.filter((item, index) => {
return this.videoCategories.indexOf(item) === index;
});
Which works fine, I get an array of the categories without dupes. But I'm trying to learn and dry up the code a bit by stringing them together, and this does not work - yields empty array
constructor(private videoService: VideoService) {
this.videos = videoService.getVideos();
this.videoCategories = this.videos
.map(v => v.category)
.filter((item, index) => {
return this.videoCategories.indexOf(item) === index;
});
console.log(this.videoCategories);
}
Array is empty because when you does filtering array return this.videoCategories.indexOf(item) === index;
, field this.videoCategories
was empty.
Try it:
this.videoCategories = this.videos
.map(v => v.category)
.filter((item, index, array) => {
return array.indexOf(item) === index;
});