尝试将不同的元素放入另一个数组时,正确的映射和过滤方法是什么?
我尝试了几种不同的方法,但始终收到“非法的返回语句”的语法错误。
我的目标是显示与以下数组不同的项目。因此,如果“ Level” =“ b”,则只会将其添加到“ levelsList”数组一次。
//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();
});
答案 0 :(得分:1)
你好我的建议
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();
在此处https://codeburst.io/javascript-array-distinct-5edc93501dc4中查看更多示例 还创建了一个测试https://next.plnkr.co/edit/bXWCDc4GjUITshgN?open=lib%2Fapp.ts&deferRun=1
的插件