Check if Array Elements Are Equal

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring JavaScript programming by implementing a function that checks whether all elements in an array are equal. We will be using the Array.prototype.every() method to compare the elements of the array with the first element and return a boolean value based on whether they are equal or not. This lab is designed to help you get a better understanding of JavaScript arrays and built-in methods.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic 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/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28140{{"`Check if Array Elements Are Equal`"}} javascript/data_types -.-> lab-28140{{"`Check if Array Elements Are Equal`"}} javascript/arith_ops -.-> lab-28140{{"`Check if Array Elements Are Equal`"}} javascript/comp_ops -.-> lab-28140{{"`Check if Array Elements Are Equal`"}} javascript/array_methods -.-> lab-28140{{"`Check if Array Elements Are Equal`"}} end

Checking for Equality of Array Elements

To check if all the elements in an array are the same, you can use the Array.prototype.every() method, which compares all elements with the first one.

Here's how you can implement it:

const allEqual = (arr) => arr.every((val) => val === arr[0]);

Note that the strict comparison operator is used to compare the elements. This operator doesn't account for NaN self-inequality.

Example usage:

allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true

Summary

Congratulations! You have completed the Check if Array Elements Are Equal lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like