1

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! :)

4
  • 1
    Look, someone asked it before : stackoverflow.com/questions/10927722/… Commented Sep 19, 2013 at 12:11
  • Given the result, do you mean 'remove every key in the second array that is not in the first array'? Commented Sep 19, 2013 at 12:12
  • And that first 'array' is an object with arrays as property values, not an array. Commented Sep 19, 2013 at 12:13
  • @Jahnux73 I seek through SO before asking, but didn't found that, thank you! Commented Sep 19, 2013 at 13:27

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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.