Introduction
In this lab, we will explore the concept of array intersection in JavaScript. Specifically, we will be implementing a function that returns the common elements between two arrays, after applying a provided function to each element of both arrays. This lab will help you understand how to use higher-order functions in JavaScript to manipulate arrays and solve common programming problems.
Instructions for Finding Mapped Array Intersection
To find common elements in two arrays after applying a function to each element of both arrays, follow these steps:
- Open Terminal/SSH and type
node. - Use the code provided below:
const intersectionBy = (a, b, fn) => {
const s = new Set(b.map(fn));
return [...new Set(a)].filter((x) => s.has(fn(x)));
};
- In the code, replace
aandbwith your arrays andfnwith the function you want to apply to each element. - Run the code to get the resulting array with common elements.
Example:
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
intersectionBy(
[{ title: "Apple" }, { title: "Orange" }],
[{ title: "Orange" }, { title: "Melon" }],
(x) => x.title
); // [{ title: 'Orange' }]
In the first example, the function Math.floor is applied to the arrays [2.1, 1.2] and [2.3, 3.4], returning the common element [2.1].
In the second example, the function x => x.title is applied to the arrays [{ title: 'Apple' }, { title: 'Orange' }] and [{ title: 'Orange' }, { title: 'Melon' }], returning the common element [{ title: 'Orange' }].
Summary
Congratulations! You have completed the Mapped Array Intersection lab. You can practice more labs in LabEx to improve your skills.