Introduction
In this lab, we will explore the concept of checking if an array has only one match in JavaScript. We will utilize the Array.prototype.filter() method to find all matching array elements and then use the Array.prototype.length property to determine if only one element matches the given function. By the end of the lab, you will have a better understanding of how to effectively check for a single match in an array using JavaScript.
Function to Check if Array Has Only One Match
To check if an array has only one value matching the given function, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.filter()in combination withfnto find all matching array elements. - Use
Array.prototype.lengthto check if only one element matchesfn.
Here's the code:
const hasOne = (arr, fn) => arr.filter(fn).length === 1;
And here's an example:
hasOne([1, 2], (x) => x % 2); // true
hasOne([1, 3], (x) => x % 2); // false
Summary
Congratulations! You have completed the Check if Array Has Only One Match lab. You can practice more labs in LabEx to improve your skills.