I'm trying to filter an array with partial matches from the entirety of another array. For example, the arrays are outlined below:
Array1 =
categories: 292300,
categories: 300,
categories: 292500280
Array2 =
300,
498
With the filter, I would expect to return:
NewArray =
categories: 292300,
categories: 300
What is the best way to implement this? I've tried the code below with no luck:
const NewArray = Array1.filter(Array1 => !(Array1.categories.includes(Array2)))
CodePudding user response:
Why new array also includes 292300 while it's not included in array2?
But if you want to filter array1 with data included in array2, there is the solution
const NewArray = Array1.filter(({ categories }) => Array2.includes(categories))
CodePudding user response:
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);
}
});
});
CodePudding user response:
To do partal matching just need parse int to 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}
