假设我们有一个数组和类似这样的对象-
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函数,该函数接受两个这样的数组,并对第一个数组进行过滤以仅包含那些名称属性包含在第二个数组中的对象。
因此,让我们为该函数编写代码-
为此的代码将是-
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 } ]