-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

1

1 Answer 1

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' }
]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.