如果不存在于另一个数组中,则从数组中删除 [英] Remove from array if not present in another array

查看:121
本文介绍了如果不存在于另一个数组中,则从数组中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在寻找一种方法来删除1005&来自arrayToCheck的1006因为那些id不在allowedIds数组中

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.

谢谢!

推荐答案

您可以使用 idsToCheck ://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\"rel =noreferrer> Array.prototype.filter() 过滤掉所有不在 allowedIds 中的ID。例如:

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));

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

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;
});

这篇关于如果不存在于另一个数组中,则从数组中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆