Check if Array Has Only One Match

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28144{{"`Check if Array Has Only One Match`"}} javascript/data_types -.-> lab-28144{{"`Check if Array Has Only One Match`"}} javascript/arith_ops -.-> lab-28144{{"`Check if Array Has Only One Match`"}} javascript/comp_ops -.-> lab-28144{{"`Check if Array Has Only One Match`"}} javascript/higher_funcs -.-> lab-28144{{"`Check if Array Has Only One Match`"}} end

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.

Other JavaScript Tutorials you may like