-1

Given two array of objects:

 let a = [
{
  "state": "Alabama"
},
{
  "state": "Alaska"
},
{
  "state": "Arizona"
},
{
  "state": "California"
}
]

let b = [
{
  "state": "Arizona",
  "link": "arizona.com"
},
{
  "state": "Alaska",
  "link": "Alaska.com"
}

How can I return an array that is a combination of the two arrays, but prioritizing what's in array b?

Example result:

result = [
{
  "state": "Alabama"
},
{
  "state": "Alaska",
  "link": "Alaska.com"
}
{
  "state": "Arizona",
  "link": "arizona.com"
},
{
  "state": "California"
}
]

It does not matter whether or not the object is sorted or not.

My initial idea is to create an empty result array, and push into it what's in array 'a' but not in array 'b'. and then afterwards, push everything inside 'b' into the result array. However, I am not sure how to do that.

Thanks

matt1331
  • 105
  • 2
  • 6
  • 1
    also [How to Merge two array of objects based on same key and value in javascript?](https://stackoverflow.com/questions/63616406/how-to-merge-two-array-of-objects-based-on-same-key-and-value-in-javascript) (as well as [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users)) – pilchard Jan 05 '22 at 00:25

1 Answers1

1
function merge(a, b) {
  if (a.length < b.length) [a, b] = [b, a];

  b.forEach((b) => (a.find((a) => a.state == b.state)['link'] = b.link));
  return a;
}

const result = merge(a, b);

Result:

[
  { state: 'Alabama' },
  { state: 'Alaska', link: 'Alaska.com' },
  { state: 'Arizona', link: 'arizona.com' },
  { state: 'California' }
]
amlxv
  • 1,610
  • 1
  • 11
  • 18