简体   繁体   中英

Javascript filter array based on another array of object

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?

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);

I suggest a different approach and take an object for the given data and map the wanted names for eithe the given data or a new object.

This approach has a better big O, becaus it take a hash table and works fast for great data.

 const array1 = [{ name: "raj", age: 20 }, { name: "ravi", age: 40 }], array2 = ['raj', 'ravi', 'arnold'], data = array1.reduce((r, o) => (r[o.name] = o, r), {}), result = array2.map(name => data[name] || { name, age: null, available: 'no' }); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM