javascript - 使用值数组过滤数组
问题描述
我有 2 个数组,我想用另一个数组过滤一个数组。例如,如果 array1 包含 array2 中的任何值,则应返回它们。
这两个数组是:
const array1 = [a, b, c, d]
另一个数组,应在“id”等于 array1 中的任何值的情况下进行过滤:
const array2 = [
{
id: b
title: title1
},
{
id: d
title: title2
},
{
id: f
title: title3
}
]
解决方案
您可以使用Array.prototype.filter()和Array.prototype.indexOf():
const array1 = ['a', 'b', 'c', 'd'];
const array2 = [{
id: 'b',
title: 'title1'
}, {
id: 'd',
title: 'title2'
}, {
id: 'f',
title: 'title3'
}];
const result = array2.filter(function(x){
return array1.indexOf(x.id) !== -1;
});
推荐阅读
- json - 仅当原始文件中已存在密钥时,如何使用来自另一个文件的密钥更新 json 文件?
- python - 如何将使用虚数的数学脚本转换为 Python?
- azure-data-factory - 将 json blob 复制到 ADX 表
- java - 如何声明具有相同数据类型的多个参数?(爪哇)
- react-native - 禁用
触摸事件和交互 react-native-maps - android - 片段 exitTransition 与 enterTransition 重叠
- mysql - 与 ASP.NET 和 IIS 一起使用时,MySQL 临时表何时被删除?
- vb.net - 我可以在 Visual Basic 应用程序中手动设置随机化的种子吗
- azure-active-directory - 如何使用图形 API 向应用注册添加权限?
- swift - 使用应用程序语言中的国家/地区代码而不是电话区域设置语言检索国家/地区名称