What is the best way to filter and map distinct elements from an array into another array?
I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement".
My objective is to display only unique items from an array, for example, adding 'Level' = 'b' to the 'levelsList' array only once.
// Here is a simplified version of the dataset returned by myService.myMethod() that requires filtering:
[
{
"ID": 1,
"Level": "a",
"Year": 1
},
{
"ID": 2,
"Level": "b",
"Year": 2
},
{
"ID": 3,
"Level": "b",
"Year": 2
},
]
levelsList: string[] = [];
// Syntax error arises at 'level.Level'
this.myService.myMethod().subscribe(
data => {
this.levelsList = data
.filter((level) => {
return level.Level === this.usrInfo.a;
}).map((level) => {
return level.Level;
}).sort();
});
// Another syntax error can be found at p.Level while filtering
this.myService.myMethod().subscribe(
data => {
this.levelsList = data.map(p => p.Level).filter(p => p.Level === this.usrInfo.a).sort();
});
// Yet another syntax error occurs in this block
this.myService.myMethod().subscribe(
data => {
this.levelsList = data.map((p) => p.Level)
.filter((p) => p.level === this.usrInfo.a).sort();
});