| 1 | /**
|
|---|
| 2 | * Returns the intersection of two arrays based on a mapping function.
|
|---|
| 3 | *
|
|---|
| 4 | * This function takes two arrays and a mapping function. It returns a new array containing
|
|---|
| 5 | * the elements from the first array that, when mapped using the provided function, have matching
|
|---|
| 6 | * mapped elements in the second array. It effectively filters out any elements from the first array
|
|---|
| 7 | * that do not have corresponding mapped values in the second array.
|
|---|
| 8 | *
|
|---|
| 9 | * @template T - The type of elements in the first array.
|
|---|
| 10 | * @template U - The type of elements in the second array.
|
|---|
| 11 | * @param {T[]} firstArr - The first array to compare.
|
|---|
| 12 | * @param {U[]} secondArr - The second array to compare.
|
|---|
| 13 | * @param {(item: T | U) => unknown} mapper - A function to map the elements of both arrays for comparison.
|
|---|
| 14 | * @returns {T[]} A new array containing the elements from the first array that have corresponding mapped values in the second array.
|
|---|
| 15 | *
|
|---|
| 16 | * @example
|
|---|
| 17 | * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
|
|---|
| 18 | * const array2 = [{ id: 2 }, { id: 4 }];
|
|---|
| 19 | * const mapper = item => item.id;
|
|---|
| 20 | * const result = intersectionBy(array1, array2, mapper);
|
|---|
| 21 | * // result will be [{ id: 2 }] since only this element has a matching id in both arrays.
|
|---|
| 22 | *
|
|---|
| 23 | * @example
|
|---|
| 24 | * const array1 = [
|
|---|
| 25 | * { id: 1, name: 'jane' },
|
|---|
| 26 | * { id: 2, name: 'amy' },
|
|---|
| 27 | * { id: 3, name: 'michael' },
|
|---|
| 28 | * ];
|
|---|
| 29 | * const array2 = [2, 4];
|
|---|
| 30 | * const mapper = item => (typeof item === 'object' ? item.id : item);
|
|---|
| 31 | * const result = intersectionBy(array1, array2, mapper);
|
|---|
| 32 | * // result will be [{ id: 2, name: 'amy' }] since only this element has a matching id that is equal to seconds array's element.
|
|---|
| 33 | */
|
|---|
| 34 | declare function intersectionBy<T, U>(firstArr: readonly T[], secondArr: readonly U[], mapper: (item: T | U) => unknown): T[];
|
|---|
| 35 |
|
|---|
| 36 | export { intersectionBy };
|
|---|