Last active
March 1, 2025 12:59
-
-
Save youyoumu/65109a73f1fb236ec42ec68dc7ace997 to your computer and use it in GitHub Desktop.
Utility function to Merges two arrays of objects, combining properties from both arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Merges two arrays of objects, combining properties from both arrays. | |
* Allows for duplicates and preserves all properties. | |
* | |
* @template T The first type of objects in the arrays | |
* @template U The second type of objects in the arrays | |
* @param array1 First array of objects | |
* @param array2 Second array of objects | |
* @returns Merged array of objects with combined properties | |
*/ | |
export function mergeArrays<T, U>( | |
array1: T[], | |
array2: U[] | |
): ((T & Partial<U>) | (U & Partial<T>))[] { | |
if (!array1.length || !array2.length) { | |
return [...array1, ...array2] as ((T & Partial<U>) | (U & Partial<T>))[]; | |
} | |
const keys1 = Object.keys(array1[0] as object); | |
const keys2 = Object.keys(array2[0] as object); | |
return [ | |
...array1.map((item1) => { | |
for (const key of keys2) { | |
item1[key] = item1[key]; | |
} | |
return item1; | |
}), | |
...array2.map((item2) => { | |
for (const key of keys1) { | |
item2[key] = item2[key]; | |
} | |
return item2; | |
}), | |
] as ((T & Partial<U>) | (U & Partial<T>))[]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment