Union of two arrays of objects by merging on condition

I am trying to merge two sets of arrays of objects according to some conditions on each set. If a keyword on array1 is not found on array2 then add the object from array1 and add the property value pair number: 0, if it is found then juts add the properties of array1 to array2 object.

This is how far I got, but keeps on repeating the objects.

const array1 = [
  { keyword: 'present', prop: 'foo' },
  { keyword: 'another present', prop: 'bla' },
  { keyword: 'not present', prop: 'hey' }
]

const array2 = [
  { keyword: 'present', number: 12345 },
  { keyword: 'another present', number: 12345 }
]

const res = array1.reduce((acc, obj1) => {
  for (const obj2 of array2) {
    if (obj2.keyword === obj1.keyword) {
      acc.push({
        ...obj1,
        ...obj2
      })
    } else {
      acc.push({
        ...obj1,
        number: 0
      })
    }
  }

  return acc
}, [])

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

This is the desired output

[
  { keyword: 'present', prop: 'foo', number: 12345 },
  { keyword: 'another present', prop: 'bla', number: 12345 },
  { keyword: 'not present', prop: 'hey', number: 0 }
]

Answer

You need to break from the loop early as soon as one match is found.

const res = array1.reduce((acc, obj1) => {
  for (const obj2 of array2) {
    if (obj2.keyword === obj1.keyword) {
      acc.push({
        ...obj1,
        ...obj2
      })
      return acc // as soon as obj2 is found, stop processing for obj1
    }
  }

  acc.push({
    ...obj1,
    number: 0
  }) // if nothing from array2 is found

  return acc
}, [])