如果不存在于另一个数组中,则从数组中删除

时间:2023-01-14 20:12:10
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

我正在寻找一种从arrayToCheck中删除1005和1006的方法,因为这些id不在allowedIds数组中

any help would be appreciated.

任何帮助,将不胜感激。

thanks!

1 个解决方案

#1


4  

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

您可以使用Array.prototype.filter()迭代idsToCheck来过滤掉不在allowedIds中的所有ID。例如:

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.

注意:使用ES6功能:箭头函数和Array.prototype.includes()。要在旧版浏览器中使用它,请检查兼容性。

Here is an alternative implementation with better browser compatiblity:

以下是具有更好浏览器兼容性的替代实现:

var checkedIds = idsToCheck.filter(function(id) {
  return allowedIds.indexOf(id) > -1;
});

#1


4  

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

您可以使用Array.prototype.filter()迭代idsToCheck来过滤掉不在allowedIds中的所有ID。例如:

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.

注意:使用ES6功能:箭头函数和Array.prototype.includes()。要在旧版浏览器中使用它,请检查兼容性。

Here is an alternative implementation with better browser compatiblity:

以下是具有更好浏览器兼容性的替代实现:

var checkedIds = idsToCheck.filter(function(id) {
  return allowedIds.indexOf(id) > -1;
});