Shayuh
Shayuh

Reputation: 381

Filtering two arrays returns blank array

I have these two arrays and have a simple method to filter the matching items from both the data array and the data2 array. But it returns empty array when it should return two items. What am i doing wrong?

var data =  [{ teamId: 74, teamName: 'Blah' },
 { teamId: 94, teamName: 'Panhi' },
 { teamId: 30, teamName: 'Writer' },
 { teamId: 121, teamName: 'People' },
 { teamId: 85, teamName: 'Perf' },
 { teamId: 31, teamName: 'Tell' },
 { teamId: 32, teamName: 'Gall' },
 { teamId: 137, teamName: 'Bird' },
 { teamId: 79, teamName: 'Blue' },
 { teamId: 119, teamName: 'Red' },
 { teamId: 66, teamName: 'Pluto' },
 { teamId: 56, teamName: 'PolarBear' },
 { teamId: 33, teamName: 'Praxis' },
 { teamId: 62, teamName: 'Purple' }
];

var data2 = [ { id: 1, reId: 52, teamId: 94 },
  { id: 2, reId: 52, teamId: 32 } ];

var found = data.filter(i => i.teamId === data2.teamId);
console.log(found);

Upvotes: 0

Views: 54

Answers (2)

Hassan Imam
Hassan Imam

Reputation: 22574

A dynamic solution to your problem.

var data =  [{ teamId: 74, teamName: 'Blah' },
 { teamId: 94, teamName: 'Panhi' },
 { teamId: 30, teamName: 'Writer' },
 { teamId: 121, teamName: 'People' },
 { teamId: 85, teamName: 'Perf' },
 { teamId: 31, teamName: 'Tell' },
 { teamId: 32, teamName: 'Gall' },
 { teamId: 137, teamName: 'Bird' },
 { teamId: 79, teamName: 'Blue' },
 { teamId: 119, teamName: 'Red' },
 { teamId: 66, teamName: 'Pluto' },
 { teamId: 56, teamName: 'PolarBear' },
 { teamId: 33, teamName: 'Praxis' },
 { teamId: 62, teamName: 'Purple' }
];

var data2 = [ { id: 1, reId: 52, teamId: 94 },
  { id: 2, reId: 52, teamId: 32 } ];

var found = [];

found = data.filter(function(i) {
  return data2.find( d => d.teamId === i.teamId);
});
console.log(found);

Upvotes: 1

Pengyy
Pengyy

Reputation: 38189

data2 is an array, you should loop through it to filter with each of its elements.

refer the below example:

var data =  [{ teamId: 74, teamName: 'Blah' },
 { teamId: 94, teamName: 'Panhi' },
 { teamId: 30, teamName: 'Writer' },
 { teamId: 121, teamName: 'People' },
 { teamId: 85, teamName: 'Perf' },
 { teamId: 31, teamName: 'Tell' },
 { teamId: 32, teamName: 'Gall' },
 { teamId: 137, teamName: 'Bird' },
 { teamId: 79, teamName: 'Blue' },
 { teamId: 119, teamName: 'Red' },
 { teamId: 66, teamName: 'Pluto' },
 { teamId: 56, teamName: 'PolarBear' },
 { teamId: 33, teamName: 'Praxis' },
 { teamId: 62, teamName: 'Purple' }
];

var data2 = [ { id: 1, reId: 52, teamId: 94 },
  { id: 2, reId: 52, teamId: 32 } ];

var found = data.filter(i => i.teamId === data2[0].teamId || i.teamId === data2[1].teamId);
console.log(found);

Upvotes: 1

Related Questions