在 JavaScript 中使用一个数组过滤另一个数组
假设,我们有一个数组和如下对象 −
对象
const main = [ {name: "Karan", age: 34}, {name: "Aayush", age: 24}, {name: "Ameesh", age: 23}, {name: "Joy", age: 33}, {name: "Siddarth", age: 43}, {name: "Nakul", age: 31}, {name: "Anmol", age: 21}, ];
数组
const names = ["Karan", "Joy", "Siddarth", "Ameesh"];
我们需要编写一个 JavaScript 函数,其中需要使用两个这样的数组并原地过滤第一个数组,使其仅包含 name 属性包含在第二个数组中的对象。
因此,让我们编写此函数的代码 −
示例
代码如下 −
const main = [ {name: "Karan", age: 34}, {name: "Aayush", age: 24}, {name: "Ameesh", age: 23}, {name: "Joy", age: 33}, {name: "Siddarth", age: 43}, {name: "Nakul", age: 31}, {name: "Anmol", age: 21}, ]; const names = ["Karan", "Joy", "Siddarth", "Ameesh"]; const filterUnwanted = (main, names) => { for(let i = 0; i < main.length; ){ if(names.includes(main[i].name)){ i++; continue; }; main.splice(i, 1); }; }; filterUnwanted(main, names); console.log(main);
输出
控制台输出如下 −
[ { name: 'Karan', age: 34 }, { name: 'Ameesh', age: 23 }, { name: 'Joy', age: 33 }, { name: 'Siddarth', age: 43 } ]
广告