Check if Array Has Only One Match

Beginner

This tutorial is from open-source community. Access the source code

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:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.filter() in combination with fn to find all matching array elements.
  3. Use Array.prototype.length to check if only one element matches fn.

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.