Determine whether all array elements are same in JavaScript
This post will discuss how to determine whether all array elements are same or not in JavaScript.
There are several ways to determine whether all array elements are same or not in JavaScript. Here are some of the possible functions, along with some examples:
1. Using Array.every() function
The Array.every() function tests whether all elements in the array pass a test implemented by a provided function. We can pass a function that compares each element of the array to the first element, using the strict equality operator (===). This will return true if all elements are equal, and false otherwise. Here’s an example:
|
1 2 3 4 5 6 |
function allEqual(arr) { return arr.every(val => val === arr[0]); } console.log(allEqual([1, 1, 1])); // true console.log(allEqual([1, 2, 1])); // false |
2. Using a Set
The Set object allows us to store unique values of any type. To use it, we need to create a new Set object from the array using the new Set() constructor. This will eliminate any duplicate values from the array. Then, we can check the size property of the Set object, which returns the number of values in the Set. If the size is 1, it means all elements in the array are equal. If the size is greater than 1, it means there are different elements in the array. For instance:
|
1 2 3 4 5 6 |
function allEqual(arr) { return new Set(arr).size === 1; } console.log(allEqual([1, 1, 1])); // true console.log(allEqual([1, 2, 1])); // false |
3. Using a for loop
This function iterates over the array and compares each element with the first element using the strict equality operator (===). The idea is to use a flag variable to indicate whether the array is identical or not, and initialize it to true. Then, we need to loop over the array from the second element onwards, and update the result variable with the comparison result. If any comparison returns false, the result variable will become false as well. After the loop ends, we can return the result variable. For instance:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function allEqual(arr) { // if the array is empty or has one element, it is equal if (arr.length <= 1) { return true; } // store the first element as a reference let first = arr[0]; // loop through the rest of the array for (let i = 1; i < arr.length; i++) { // if any element is not equal to the first one, return false if (arr[i] !== first) { return false; } } // if the loop finishes without returning false, return true return true; } console.log(allEqual([1, 1, 1])); // true console.log(allEqual([1, 2, 1])); // false |
That’s all about determining whether all array elements are same or not in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)