@y87cgp/merge-array-items
v0.1.0
Published
A library for merging objects from two arrays
Downloads
84
Readme
@y87cgp/merge-array-elems
Merge items from one array with matching items from another array.
This library is useful when:
- one array is your primary dataset
- a second array contains optional related data
- keys may be objects, arrays, or other deep structures
- you want full control over how the final item is built
Install
npm install @y87cgp/merge-array-elemsAPI
mergeItems<T1, T2, TKey, TCombined>(
arr1: T1[],
arr2: T2[],
getKey1: (item: T1) => TKey,
getKey2: (item: T2) => TKey,
merge: (item1: T1, item2: T2 | undefined) => TCombined
): TCombined[]Example
import { mergeItems } from "@y87cgp/merge-array-elems";
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
];
const profiles = [
{ userId: 1, city: "London" },
];
const result = mergeItems(
users,
profiles,
(user) => user.id,
(profile) => profile.userId,
(user, profile) => ({
...user,
city: profile?.city ?? null,
})
);
console.log(result);
// [
// { id: 1, name: "Ada", city: "London" },
// { id: 2, name: "Linus", city: null }
// ]Behavior
- The result always has the same length and order as
arr1. - Each item in
arr1is merged with the matching item fromarr2. - If no match is found in
arr2, themergecallback receivesundefinedas the second argument. - Items that exist only in
arr2are ignored. - Keys are matched using deep equality, so non-primitive keys are supported.
Example With Object Keys
import { mergeItems } from "@y87cgp/merge-array-elems";
const orders = [
{ key: { shopId: 10, orderId: 101 }, total: 50 },
];
const statuses = [
{ ref: { shopId: 10, orderId: 101 }, status: "paid" },
];
const result = mergeItems(
orders,
statuses,
(order) => order.key,
(status) => status.ref,
(order, status) => ({
...order,
status: status?.status ?? "unknown",
})
);Requirements
- Node.js
>=18 - ESM package environment
License
MIT
