Reputation: 336
the row users array looks like.
var users = [{name: 'John',address: 'USA',year:2010 },{name: 'John',address: 'USA',year:2011 },{name: 'John',address: 'USA',year:2012 },{name: 'John',address: 'USA',year:2013 },{name: 'John',address: 'USA',year:2014}];
the filter array is,
var filter_year = ['2010','2011','2012'];
how i can get the result array of filtered using years in filter_year, i need to get result array like.
var users = [{name: 'John',address: 'USA',year:2010 },{name: 'John',address: 'USA',year:2011 },{name: 'John',address: 'USA',year:2012 }];
Upvotes: 1
Views: 161
Reputation: 51
You can use below code to get all users for given years.
var filter_year = ['2010','2011','2012'],
users = [{name: 'John',address: 'USA',year:2010 },{name: 'John',address: 'USA',year:2011 },{name: 'John',address: 'USA',year:2012 },{name: 'John',address: 'USA',year:2013 },{name: 'John',address: 'USA',year:2014}],
filteredUsers = []
allYears = filter_year.join("|");
for(var user in users) {
if(allYears.indexOf(users[user].year) !== -1) {
filteredUsers.push(users[user]);
}
}
console.log(filteredUsers);
Upvotes: 1
Reputation: 318182
Just filter one array based on inclusion in the other array
var users = [{name: 'John',address: 'USA',year:2010 },{name: 'John',address: 'USA',year:2011 },{name: 'John',address: 'USA',year:2012 },{name: 'John',address: 'USA',year:2013 },{name: 'John',address: 'USA',year:2014}];
var filter_year = ['2010','2011','2012'];
var result = users.filter( item => filter_year.includes(item.year+""));
console.log(result)
Note that the years are integers in one array, and strings in the other
Upvotes: 0