Palindrome array - JavaScript


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 i.e. palindrome.

Example

Let’s write the code for this function −

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

Updated on: 15-Sep-2020

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements