Javascript filter array based on another array of object Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Javascript filter array based on another array of object without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to merge the two arrays based on Arr1 values. If the array 2 doesn’t has the respective value in array1, it should return as empty object with values. Below are the two arrays:

Arr1 = [{
  name: "raj",
  age: 20
}, {
  name: "ravi",
  age: 40
}];


Arr2 = ['raj', 'ravi', 'arnold'];

Javascript Code is,

let result = Arr1.filter(o1 => Arr2.some(o2 => o2 === o1.name));

I am getting the result as below,

result = [{
  name: "raj",
  age: 20
}, {
  name: "ravi",
  age: 40
}];

But expected array should be,

[{
  name: "raj",
  age: 20
}, {
  name: "ravi",
  age: 40
}, {
 name: "arnold",
 age: null,
 available: no
}];

Any suggestions?

Answer

You can use Array#map along with Array#find to obtain your expected result.

let Arr1 = [{
  name: "raj",
  age: 20
}, {
  name: "ravi",
  age: 40
}];
let Arr2 = ['raj', 'ravi', 'arnold'];
let result = Arr2.map(x=>
     Arr1.find(({name})=>name===x)??{name:x,age:null,available: 'no'}
  );
console.log(result);
We are here to answer your question about Javascript filter array based on another array of object - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji