It's not entirely clear how you intend to merge the elements, whether it's by shared index in the two arrays or by shared id
values. Either way, creating simple utility functions can make this task quite straightforward.
Merging with Shared Indices
If the goal is to merge based on shared indices, you could approach it like this:
const zipWith = (fn) => (xs, ys) => xs .map ((x, i) => fn (x, ys [i]))
const combine = zipWith ((x, y) => ({...x, ...y}))
const arr1 = [{id:1, name: 'John'}, {id:2, name: 'Adam'}], arr2 = [{id:1, address: 'NY', number: 200}, {id:2, address: 'LA', number: 300}]
console .log (combine (arr1, arr2))
.as-console-wrapper {max-height: 100% !important; top: 0}
We define a reusable function zipWith
—commonly found in utility libraries—that takes a combining function and applies it to elements at corresponding indices in two arrays. (Note: Uneven array lengths might produce unexpected results.)
The combine
function, built on top of zipWith
, merges objects simply by merging their properties. While Object.assign
could be used here, I prefer a non-mutating approach.
Grouping by id
If merging based on shared ids
is the goal, a different strategy is required. By grouping elements into an object with id
as the key, the process becomes more efficient (O (m + n)
instead of O (m * n)
). The groupBy
function organizes elements based on a supplied function, and mergeBy
can then merge these groups:
const groupBy = (fn) => (xs) =>
xs .reduce ((a, x, _, __, k = fn (x)) => ((a [k] = a [k] || []), (a[k] .push (x)), a), {})
const mergeBy = (fn) => (...xss) =>
Object .values (groupBy (fn) (xss .flat ())) .map (xs => Object .assign ({}, ...xs))
const combine = mergeBy (x => x .id)
const arr1 = [{id:1, name: 'John'}, {id:2, name: 'Adam'}], arr2 = [{id:1, address: 'NY', number: 200}, {id:2, address: 'LA', number: 300}]
console .log (combine (arr1, arr2))
.as-console-wrapper {max-height: 100% !important; top: 0}
The mergeBy
function builds upon groupBy
, and combine
employs it with an id-extraction function. This implementation supports multiple values sharing the same id
and allows for merging across multiple arrays.
By utilizing these utility functions, flexibility increases. Duplicate id
s can be accommodated, and any number of arrays can be processed. This versatility underscores the value of maintaining a library of utility functions for coding tasks.
Key Takeaway
This exercise demonstrates how simple it can be to tackle such tasks with the aid of well-crafted utility functions like groupBy
and zipWith
. Adding tools like mergeBy
to your arsenal—whether in a personal collection or from a trusted library—enhances your coding capabilities significantly.
1. Once again, no objects were harmed during the production of this content.