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 }
]

Updated on: 22-Oct-2020

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements