Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (9.5k points)

Below is an example of array I’ve:

var users = [{

    name: 'John',

    email: '[email protected]',

    age: 25,

    address: 'USA'

    },

    {

        name: 'Tom',

        email: '[email protected]',

        age: 35,

        address: 'England'

    },

    {

        name: 'Mark',

        email: '[email protected]',

        age: 28,

        address: 'England'

}];

I want to simplify the array of objects and need to filter object like below:

var filter = {address: 'England', name: 'Mark'};

If I want to  filter all users by address and name, I loop through filter object properties like below:

function filterUsers (users, filter) {

    var result = [];

    for (var prop in filter) {

        if (filter.hasOwnProperty(prop)) {

            //at the first iteration prop will be address

            for (var i = 0; i < filter.length; i++) {

                if (users[i][prop] === filter[prop]) {

                    result.push(users[i]);

                }

            }

        }

    }

    return result;

}

The above code runs fine except for the second iteration where only the last user should be added to the array result, but it gives me 2 elements in the array. Can anyone tell me what I’m doing wrong here?

1 Answer

0 votes
by (19.7k points)

Check out the below code implementation:

var filter = {

  address: 'England',

  name: 'Mark'

};

var users = [{

    name: 'John',

    email: '[email protected]',

    age: 25,

    address: 'USA'

  },

  {

    name: 'Tom',

    email: '[email protected]',

    age: 35,

    address: 'England'

  },

  {

    name: 'Mark',

    email: '[email protected]',

    age: 28,

    address: 'England'

  }

];


 

users= users.filter(function(item) {

  for (var key in filter) {

    if (item[key] === undefined || item[key] != filter[key])

      return false;

  }

  return true;

});

console.log(users)

Interested in Java? Check out this Java Certification by Intellipaat.   

Related questions

Browse Categories

...