w3resource

JavaScript: Check whether all elements in a given array are equal or not

JavaScript fundamental (ES6 Syntax): Exercise-56 with Solution

Write a JavaScript program to check whether all elements in a given array are equal or not.

  • Use Array.prototype.every() to check if all the elements of the array are the same as the first one.
  • Elements in the array are compared using the strict comparison operator, which does not account for NaN self-inequality.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define a function 'allEqual' to check if all elements in the array are equal.
const allEqual = arr =>
  // Use the 'every' method to check if all elements in the array are equal to the first element.
  arr.every(val => val === arr[0]);

// Test cases
console.log(allEqual([1, 2, 3, 4, 5, 6])); // Output: false (not all elements are equal)
console.log(allEqual([12, 12, 12, 12]));    // Output: true (all elements are equal)

Output:

false
true

Visual Presentation:

JavaScript Fundamental: Check whether all elements in a given array are equal or not
JavaScript Fundamental: Check whether all elements in a given array are equal or not

Flowchart:

flowchart: Check whether all elements in a given array are equal or not

Live Demo:

See the Pen javascript-basic-exercise-56-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to Join all given URL segments together, then normalizes the resulting URL.
Next: Write a JavaScript program to compute the average of an array, after mapping each element to a value using the provided function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-56.php