0

I have an array of objects that I get from an ajax call, each object has properties like in this example:

Name: Bob Dylan

Value: 452342

I also have an inclusion array of values, that if not empty I need to filter the array of objects above to contain only the ones with values from the inclusion array.

Update: Example of inclusion array is simply: [452342, 4563546,34563,34563456,345634]

My best guess was to have 2 loops, outer one going through the array of objects and inner one checking if they exist in the inclusion list, and if not slicing that object. Is there a better, less laborious way of doing this?

5
  • 2
    can you provide an example of what does contains your inclusion array ? Commented Jun 2, 2015 at 15:12
  • Arrays have a .filter method, you can use .includes (or .indexOf if you're on old browsers and/or don't want to polyfill) to check for membership in the other array after .maping to a property. Commented Jun 2, 2015 at 15:13
  • 1
    Does the inclusion array contain the same object references than the array of objects? Or only objects which look like the same? Commented Jun 2, 2015 at 15:14
  • Providing a sample of the actual return data would be very helpful in being able to successfully answer your question. Commented Jun 2, 2015 at 15:18
  • Updated with example of inclusion array, changed some wording to be more clear. Commented Jun 2, 2015 at 15:23

1 Answer 1

1

Use array.filter method and then the filter method.

function isInInclusion(value) {
  var inclusionArray = [2, 130, 12];
  return inclusionArray.indexOf(value) >= 0;
};

var filtered = [12, 5, 8, 130, 44].filter(isInInclusion);

Here you have some references depends what you're using (jquery, mootools, and so on) : How do I check if an array includes an object in JavaScript?

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

2 Comments

This answer is the closest, I was able to get this to work by replacing [12, 5, 8, 130, 44] with my array of objects and changing return inclusionArray.indexOf(value) >= 0; to return inclusionArray.indexOf(value.Value) >= 0;
Of course. I provided you an example as i didn't know your data structure.

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.