z-x
z-x

Reputation: 451

jQuery/JavaScript: Filter array with another array

Let's say I have two arrays:

{First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two, Three]}

[First, Third]

Now I need to remove every key in first array that is not in second array. So - with those two in example - I should be left with:

{First: [One, Two, Three], Third: [One, Two, Three]}

I tried to use $.grep for that, but I can't figure out how to use array as a filter. Help needed! :)

Upvotes: 1

Views: 3564

Answers (2)

user2399923
user2399923

Reputation: 126

Other thing you can do without creating a new object is to delete properties

var obj = {First: ["One", "Two", "Three"], Second: ["One", "Two", "Three"], Third: ["One", "Two", "Three"]};
var filter = ["Second", "Third"];


function filterProps(obj, filter) {
  for (prop in obj) {
      if (filter.indexOf(prop) == -1) {
          delete obj[prop];
      } 
  };
  return obj;
};

//Usage: 
obj = filterObject(obj, filter);

Upvotes: 3

Tibos
Tibos

Reputation: 27823

The fastest way is to create a new object and only copy the keys you need.

var obj = {First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two, Three]}
var filter = {First: [One, Two, Three], Third: [One, Two, Three]}


function filterObject(obj, filter) {
  var newObj = {};

  for (var i=0; i<filter.length; i++) {
    newObj[filter[i]] = obj[filter[i]];
  }
  return newObj;
}


//Usage: 
obj = filterObject(obj, filter);

Upvotes: 4

Related Questions