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 
const allEqual = arr => arr.every(val => val === arr[0]);
console.log(allEqual([1, 2, 3, 4, 5, 6]));
console.log(allEqual([12, 12, 12, 12]));

Sample Output:

false
true

Pictorial 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.



JavaScript: Tips of the Day

Chunks an array into n smaller arrays

Example:

const tips_chunkIntoN = (arr, n) => {
  const size = Math.ceil(arr.length / n);
  return Array.from({ length: n }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
}
console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4)); 

Output:

[[1,2],[3,4],[5,6],[7,8]]