- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter one array with another array - JavaScript
Suppose, we have an array and objects like the following −
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"];
We are required to write a JavaScript function that takes in two such arrays and filters the first array in place to contain only those objects whose name property is included in the second array.
Example
Following is the code −
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);
This will produce the following output on console −
[ { name: 'Karan', age: 34 }, { name: 'Ameesh', age: 23 }, { name: 'Joy', age: 33 }, { name: 'Siddarth', age: 43 } ]
Advertisements