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?

Thufir Hawat
  • 456
  • 5
  • 15
  • 2
    can you provide an example of what does contains your inclusion array ? – ChainList Jun 02 '15 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 `.map`ing to a property. – Benjamin Gruenbaum Jun 02 '15 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? – Oriol Jun 02 '15 at 15:14
  • Providing a sample of the actual return data would be very helpful in being able to successfully answer your question. – talemyn Jun 02 '15 at 15:18
  • Updated with example of inclusion array, changed some wording to be more clear. – Thufir Hawat Jun 02 '15 at 15:23

1 Answers1

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?

Community
  • 1
  • 1
Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54
  • 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; – Thufir Hawat Jun 02 '15 at 15:38
  • Of course. I provided you an example as i didn't know your data structure. – Razvan Dumitru Jun 02 '15 at 15:47