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

Updated on: 23-Nov-2020

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements