DEV Community

Merge two arrays as a set

So, I love the idea of using mathematical set theory in my programming. Specifically, I really want to make use of Javascript's recent addition Set for the convenience of guaranteeing non-duplicate values and convenience APIs for iterating:

Example

const s = new Set([
  1,
  2,
  3
])

s.add(3) // 1, 2, 3
s.has(3) // true
s.forEach(...) // etc
Enter fullscreen mode Exit fullscreen mode

Problem is, it only works with primitives: e.g. Number, String and not arrays or objects due to (referential) equality limitations in JS (e.g. { a: 1 } !== { a: 1 }.

Which is kinda annoying.

So I wrote functional utility to add an arbitrary array of objects to an existing array, using a specific prop. My thoughts are: is this the most efficient way to do it? What better ways are there to do this?

This is O(n^2) which isn't exactly desirable?

const mergeArraysAsSet = (ex, merge, compareProp = 'id') => {
  return ex.concat(
    merge.reduce((mergeArray, next) => {
      if (!ex.find((x) => x[compareProp] === next[compareProp])) {
        mergeArray.push(next)
      }
      return mergeArray
    }, [])
  )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)