用另一个数组过滤一个数组-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函数,该函数接受两个这样的数组,并对第一个数组进行过滤以仅包含那些名称属性包含在第二个数组中的对象。
示例
以下是代码-
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 } ]