1

Dears,

I have:

const a1 = [{id: 21, name: "LM"},
{id: 20, name: "Off"}];

const a2 = [20,21,22];

i do following

const temp = a1.filter(({ id })=> {
a2.includes(id)
});
console.log(temp);

returns empty array, and i do not know why, can please some one help me

MaPta
  • 71
  • 6

2 Answers2

2

Arrow functions surrounded by curly brackets must use return keyword explicitly to return from the function.

You have missed the return keyword:

const a1 = [{id: 21, name: "LM"},{id: 20, name: "Off"}];
const a2 = [20,21,22];
const temp = a1.filter(({ id })=> {
  return a2.includes(id);
});
console.log(temp);

OR: In single line without the return:

const a1 = [{id: 21, name: "LM"},
{id: 20, name: "Off"}];
const a2 = [20,21,22];
const temp = a1.filter(({ id })=> a2.includes(id));
console.log(temp);
Mamun
  • 58,653
  • 9
  • 33
  • 46
  • Dear,i still get empty array as a result, when i take the cone and put it in my angular app. When i console.log my array: a1 = 0: {id: 20, name: "Off", timePeriod: "MONTH", scoreType: "SUM"} 1: {id: 21, name: "LM", timePeriod: "MONTH", scoreType: "SUM"} 2: {id: 22, name: "TT", timePeriod: "MONTH", scoreType: "AVERAGE"} a2 = [0:20] – MaPta Feb 23 '20 at 09:09
  • my angular/ionic part of ocde, which makes it not to work: constructor() { Promise.all([ this.rService.getRDef(), //2 this.rService.getRankings(), //3 this.dService.getSComponent(this.tTitle, this.Id) ]).then((res: any) => {this.getAllData(res);}) } ngOnInit() {...} getAllData(res){ this.calculateRankings(res[2], res[3]);} getScreenData(res) { res.rankings.forEach(r => { this.rIds.push(r.rankingId);});} calculateRankings(rDef: any) { this.rDef = rDef; const temp = this.rDef.filter(({ id })=> this.rIds.includes(id)); – MaPta Feb 23 '20 at 10:08
0

You missed returning for filter() to work. Filter requires you to return a boolean which you forgot to do here.

const a1 = [{id: 21, name: "LM"},
{id: 20, name: "Off"}];

const a2 = [20,21,22];

const temp = a1.filter(({ id })=> {
  return a2.includes(id)
});
console.log(temp);

Gene Sy
  • 867
  • 1
  • 6
  • 14