Checking for special type of Arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals and checks if elements are the same or not if read from front or back. Such arrays are also known by the name of palindrome arrays.

Some examples of palindrome arrays are −

const arr1 = [‘a’, ‘b’, ‘c’, ‘b’, ‘a’];
const arr2 = [4, 7, 7, 4];
const arr3 = [7, 7, 7, 7, 7, 7];

Example

The code for this will be −

const arr = [1, 5, 7, 4, 15, 4, 7, 5, 1];
const isPalindrome = arr => {
   const { length: l } = arr;
   const mid = Math.floor(l / 2);
   for(let i = 0; i <= mid; i++){
      if(arr[i] !== arr[l-i-1]){
         return false;
      };
   };
   return true;
};
console.log(isPalindrome(arr));

Output

The output in the console −

true
raja
Published on 15-Oct-2020 12:39:47
Advertisements