haydnD
haydnD

Reputation: 2293

How do I map and filter distinct on an array with typescript?

What is the proper way of mapping and filtering when trying to get distinct elements into another array?

I've tried several different ways but I keep getting an syntax error of "Illegal return statement".

My goal is to show distinct item from an array such as below. So if 'Level' = 'b' it would add it to the 'levelsList' array only once.

//small example of the data set returned from myService.myMethod() that I'm trying to filter on:
[
 {
    "ID": 1,
    "Level": "a",
    "Year": 1
  },
  {
    "ID": 2,
    "Level": "b",
    "Year": 2
  },
  {
    "ID": 3,
    "Level": "b",
    "Year": 2
  },
]


levelsList: string[] = [];

//returns syntax error on the 'level.Level'
         this.myService.myMethod().subscribe(
           data => {
             this.levelsList = data
               .filter((level) => {
                 return level.Level === this.usrInfo.a;
               }).map((level) => {
                 return level.Level;
               }).sort();
           });

 //returns syntax error at filter p.Level
         this.myService.myMethod().subscribe(
           data => {
             this.levelsList = data.map(p => p.Level).filter(p => p.Level === this.usrInfo.a).sort();
           });

 //returns syntax error
         this.myService.myMethod().subscribe(
           data => {
             this.levelsList = data.map((p) => p.Level)
               .filter((p) => p.level === this.usrInfo.a).sort();
           });

Upvotes: 0

Views: 1382

Answers (1)

Americo Arvani
Americo Arvani

Reputation: 858

Hello following my suggestion

        const levelselect = "a";

        this.result = this.json
               .filter((f) => {
                 return f.Level == levelselect
               })
               .map((level) => {
                 return level.Level;
               })
               .filter((value,index,self) => {
                 return self.indexOf(value) == index
               })
               .sort(); 

check for more example here https://codeburst.io/javascript-array-distinct-5edc93501dc4 also created a plunker to test https://next.plnkr.co/edit/bXWCDc4GjUITshgN?open=lib%2Fapp.ts&deferRun=1

Upvotes: 1

Related Questions