2

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@GTemp No problem.
yes. stack overflow asking to wait to accept correct answer min 2mins. :)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.