Introduction
In this lab, we will explore the concept of checking if an array has many matches using JavaScript. You will learn how to use the Array.prototype.filter() method in combination with a given function to find all matching array elements and then check if there are more than one such elements using the Array.prototype.length property. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript.
Function to Check if Array Has Multiple Matches
To check if an array has more than one value matching a 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 more than one element matchesfn.
Here's the code you can use:
const hasMany = (arr, fn) => arr.filter(fn).length > 1;
And here are some examples:
hasMany([1, 3], (x) => x % 2); // true
hasMany([1, 2], (x) => x % 2); // false
Summary
Congratulations! You have completed the Check if Array Has Many Matches lab. You can practice more labs in LabEx to improve your skills.