GTemp
GTemp

Reputation: 209

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?

Upvotes: 2

Views: 93

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386680

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

Upvotes: 2

Unmitigated
Unmitigated

Reputation: 89374

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

Upvotes: 3

Related Questions