Was it helpful?

Question

Filter one array with another array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 }
]
raja
Published on 01-Oct-2020 13:43:02
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top