- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Checking if all the elements are same in an array
We are required to write a JavaScript function that takes in an array of literals. The function should find whether or not all the values in the array are same. If they are same, the function should return true, false otherwise.
Example
const arr1 = [1, 2, 3]; const arr2 = [1, 1, 1]; const checkIfSame = (arr = []) => { // picking array's length const { length: l } = arr; // returning true for single element and empty array if(l <= 1){ return true; }; // sorting array arr.sort(); // checking if first and the last element are same return arr[0] === arr[l - 1]; }; console.log(checkIfSame(arr1)); console.log(checkIfSame(arr2));
Output
And the output in the console will be −
false true
- Related Articles
- Checking if all array values are smaller than a limit using JavaScript
- Checking the equality of array elements (sequence dependent) in JavaScript
- Python - Check if all elements in a List are same
- How to duplicate elements of an array in the same array with JavaScript?
- Checking an array for palindromes - JavaScript
- Check if all array elements are distinct in Python
- Building frequency map of all the elements in an array JavaScript
- Checking for uniqueness in an array in JavaScript
- How to determine if all elements are the same in a Java List?
- Return an array of all the indices of minimum elements in the array in JavaScript
- Checking existence of all continents in array of objects in JavaScript
- Checking the intensity of shuffle of an array - JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Check if an array is growing by the same margin in JavaScript
- How to filter an array from all elements of another array – JavaScript?

Advertisements