3
var allowedIds = [1000, 1001, 1002, 1003, 1004];
var idsToCheck = [1000, 1001, 1005, 1006];

I'm looking to find a way to remove 1005 & 1006 from arrayToCheck as those ids are not in the allowedIds array

any help would be appreciated.

thanks!

1
  • do a array .filter on idstocheck.. you can filter out the values that is not present in allowedIds by using the .indexOf. Commented May 4, 2017 at 15:33

1 Answer 1

11

You can iterate over idsToCheck using Array.prototype.filter() to filter out all ids which are not in allowedIds. For example:

const checkedIds = idsToCheck.filter(id => allowedIds.includes(id));

Note: using ES6 features: arrow functions and Array.prototype.includes(). To use it in older browsers check for compatibility.

Here is an alternative implementation with better browser compatiblity:

var checkedIds = idsToCheck.filter(function(id) {
  return allowedIds.indexOf(id) > -1;
});
Sign up to request clarification or add additional context in comments.

1 Comment

You should mark this question as correct, since it worked for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.