1

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 }];
1
  • You'll have to iterate the json and push only those json objects whose year exist in filter_year Commented Sep 7, 2017 at 4:30

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Why did you use item.year + "" instead of item.year.toString()? Does it have any performance benefits?
@NisargShah - Don't know, but it probably doesn't matter performance-wise, they both do the same thing, coerce to a string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.