Introduction
In this lab, we will dive into a JavaScript programming concept that involves checking if all elements in an array are unique based on a provided mapping function. This lab will demonstrate how to use Array.prototype.map() and Set to efficiently check for unique values and compare them to the original array. By the end of this lab, you will have a solid understanding of how to implement this logic in your JavaScript projects.
Checking If All Elements in an Array Are Unique with a Function
To check if all elements in an array are unique based on a provided mapping function, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
Array.prototype.map()method to apply the provided functionfnto all elements in thearrarray. - Create a new
Setfrom the mapped values to keep only unique occurrences. - Compare the length of the unique mapped values to the original array length using the
Array.prototype.lengthandSet.prototype.sizemethods.
Here is the code:
const allUniqueBy = (arr, fn) => arr.length === new Set(arr.map(fn)).size;
You can use the allUniqueBy() function to check if all elements in an array are unique. For example:
allUniqueBy([1.2, 2.4, 2.9], Math.round); // true
allUniqueBy([1.2, 2.3, 2.4], Math.round); // false
Summary
Congratulations! You have completed the Check if All Array Elements Are Unique Based on Function lab. You can practice more labs in LabEx to improve your skills.