- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Using one array to help filter the other in JavaScript
Suppose, we have an array and objects like these −
Objects:
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}, ];
Array:
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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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);
Output
The output in the console will be −
[ { name: 'Karan', age: 34 }, { name: 'Ameesh', age: 23 }, { name: 'Joy', age: 33 }, { name: 'Siddarth', age: 43 } ]
- Related Articles
- Filter one array with another array - JavaScript
- Remove elements from array using JavaScript filter - JavaScript
- How to filter values from an array using the comparator function in JavaScript?
- Filter array with filter() and includes() in JavaScript
- Filter array based on another array in JavaScript
- How to find duplicates in an array using set() and filter() methods in JavaScript?
- How to filter out common array in array of arrays in JavaScript
- JavaScript in filter an associative array with another array
- Filter null from an array in JavaScript?
- JavaScript filter array by multiple strings?
- Filter JavaScript array of objects with another array
- Filter unique array values and sum in JavaScript
- How to remove an object using filter() in JavaScript?
- Remove/ filter duplicate records from array - JavaScript?
- How to filter an array from all elements of another array – JavaScript?

Advertisements