如何从另一个数组的所有元素对一个数组进行部分匹配过滤
How to do a partial match filter on an array from all elements of another array
我正在尝试从另一个数组的整体中筛选出部分匹配的数组。例如,数组概述如下:
Array1 =
categories: 292300,
categories: 300,
categories: 292500280
Array2 =
300,
498
有了过滤器,我希望 return:
NewArray =
categories: 292300,
categories: 300
实现这个的最佳方法是什么?我试过下面的代码但没有成功:
const NewArray = Array1.filter(Array1 => !(Array1.categories.includes(Array2)))
为什么新数组还包含 292300 而它不包含在 array2 中?
但是如果你想用array2中包含的数据过滤array1,有解决方案
const NewArray = Array1.filter(({ categories }) => Array2.includes(categories))
const Array1 = [{ categories: 292300 }, { categories: 300 }, { categories: 292500280 }];
const Array2 = [300, 498];
const newArray = [];
Array2.forEach((el) => {
Array1.forEach((element) => {
if (element.categories.toString().includes(el.toString())) {
newArray.push(element);
}
});
});
要进行部分匹配只需要将 int
解析为 string
const arr1 = [{categories: 292300}, {categories: 300}, {categories: 292500280}];
const arr2 = [300, 498];
const result = arr1.filter(({ categories }) =>
arr2.some((e) => String(categories).includes(String(e))));
console.log(result);
.as-console-wrapper {max-height: 100% !important; top: 0}
我正在尝试从另一个数组的整体中筛选出部分匹配的数组。例如,数组概述如下:
Array1 =
categories: 292300,
categories: 300,
categories: 292500280
Array2 =
300,
498
有了过滤器,我希望 return:
NewArray =
categories: 292300,
categories: 300
实现这个的最佳方法是什么?我试过下面的代码但没有成功:
const NewArray = Array1.filter(Array1 => !(Array1.categories.includes(Array2)))
为什么新数组还包含 292300 而它不包含在 array2 中?
但是如果你想用array2中包含的数据过滤array1,有解决方案
const NewArray = Array1.filter(({ categories }) => Array2.includes(categories))
const Array1 = [{ categories: 292300 }, { categories: 300 }, { categories: 292500280 }];
const Array2 = [300, 498];
const newArray = [];
Array2.forEach((el) => {
Array1.forEach((element) => {
if (element.categories.toString().includes(el.toString())) {
newArray.push(element);
}
});
});
要进行部分匹配只需要将 int
解析为 string
const arr1 = [{categories: 292300}, {categories: 300}, {categories: 292500280}];
const arr2 = [300, 498];
const result = arr1.filter(({ categories }) =>
arr2.some((e) => String(categories).includes(String(e))));
console.log(result);
.as-console-wrapper {max-height: 100% !important; top: 0}