Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove from array if not present in another array

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 Answers

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;
});
like image 54
madox2 Avatar answered Dec 06 '25 02:12

madox2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!