- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements