Introduction
In this lab, we will explore JavaScript programming concepts through hands-on exercises. The lab is designed to help participants build a solid understanding of core JavaScript concepts such as functions, arrays, objects, and loops. Through a series of challenges and projects, participants will have the opportunity to apply what they learn and build their confidence as JavaScript developers.
Function to Combine Arrays with a Provided Mapping Function
To begin coding, open the Terminal/SSH and type node.
This function returns an array of elements that exist in either of the two input arrays, after applying the provided mapping function to each element in both arrays.
Here are the steps to achieve this:
- Create a new
Setby applying the mapping function to all values in the first input arraya. - Create another
Setconsisting of all the elements inbthat do not match any values in the previously createdSetwhen the mapping function is applied. - Combine the two sets and convert them to an array.
- Return the resulting array.
Here is the code for the unionBy function:
const unionBy = (a, b, fn) => {
const setA = new Set(a.map(fn));
return Array.from(new Set([...a, ...b.filter((x) => !setA.has(fn(x)))]));
};
Here are some examples of how to use the unionBy function:
unionBy([2.1], [1.2, 2.3], Math.floor); // Output: [2.1, 1.2]
unionBy([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }], (x) => x.id);
// Output: [{ id: 1 }, { id: 2 }, { id: 3 }]
Summary
Congratulations! You have completed the Mapped Array Union lab. You can practice more labs in LabEx to improve your skills.