javascriptarraysangularjsjsonfilter

Angular.js filter by element of array


I have an array of JSON objects like:

 $scope.users = [
    {name:'Maria',age:25,skills["Angular.js","Node.js"]},
    {name:'Maxime',age:28,skills["HTML","MongoDB"]},
    {name:'Noemie',age:28,skills["CSS","MongoDB"]}
 ]

I want to make a search engine. If the user can enter one or multiple words and then my app will filter my variable.

For example, the user enter "28" and "MongoDB", then I put the two queries in an array like

$scope.queries = [28,"MongoDB"]

and filter my array : $scope.users with it.

Please note that $scope.users is not as simple as the example and it has some other arrays which contain arrays etc... So I'll prefer a function to "simply" search for keywords

I would like to know how to do a function or filter.


Solution

  • Not very optimal, but you can try this

    var filterQueries = [28,"MongoDB"];
    var filteredResults = $scope.users.filter(function(obj){
      var match = false;
      filterQueries.forEach(function(query){
        if ( obj.name == query || obj.age == query || obj.skills.indexOf( query ) != -1 ) 
        {
           match = true; //assuming you want any of the query to be found rather than all
        }
      });
      return match;
    });
    

    DEMO

    	 
    var users = [
        {name:'Maria',age:25,skills : ["Angular.js","Node.js"]},
        {name:'Maxime',age:28,skills : ["HTML","MongoDB"]},
        {name:'Noemie',age:28,skills : ["CSS","MongoDB"]}
    ];
    
    var filterQueries = [28,"MongoDB"];
    var filteredResults = users.filter(function(obj){
      var match = false;
      filterQueries.forEach(function(query){
        if ( obj.name == query || obj.age == query || obj.skills.indexOf( query ) != -1 ) 
        {
           match = true; //assuming you want any of the query to be found rather than all
        }
      });
      return match;
    });
    
    document.body.innerHTML += JSON.stringify( filteredResults, 0, 4 )