July 7, 2020
How to Check if All Values in an Array are Equal in Javascript
- We have selected two elements
button
andh1
using thedocument.querySelector()
method and stored them inbtnCheck
andresult
variables respectively. - We have a global variable
users
.users
holds an array of strings. - We have attached the
click
event listener to thebutton
element. every()
method takes an anonymous function as a parameter and returns a Boolean value. As you know, arrays have a 0-based index. This anonymous function will run for each item and simply check if each item is equivalent to the first item in the array.- We are setting the inner text of the
h1
element to the Boolean value returned by theevery()
method.
let btnCheck = document.querySelector('button'); let result = document.querySelector('h1'); let users = ['Peter', 'Peter']; btnCheck.addEventListener('click', () => { let isEqual = users.every(user => user == users[0]); result.innerText = isEqual ? 'True' : 'False'; });
If you are dynamically adding items to an array, then there is a possibility that maybe you are adding the same item again and again. The question here is, how you can figure this out and avoid such a thing from happening.
There are different solutions for this problem, but we will go with the simplest solution. Array type has
every()
method which you can use to check if all items in an array are meeting a certain condition.In the following example, we have one global array and we simply want to verify if all items are equal using
every()
method. Please have a look over the code example and steps given below.HTML & CSS
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements.button
element is“Check”
and for theh1
element is“Result”
.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript