This page looks best with JavaScript enabled

Check whether array is a palindrome in Javascript

 ·   ·  ☕ 1 min read

Check whether a given array has a palindrome in Javascript.

Below logic should be fast, if not the fastest.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
console.log(checkPalindrome([1, 3, 5, 3, 1]));

function checkPalindrome(arr) {
  const len = arr.length;
  if (len % 2 == 0) return false;

  for (let i = 0; i < len / 2; i++) {
    if (arr[i] !== arr[len - i - 1]) return false;
  }
  return true;
}

The code is simple -

  1. If given array length is even, it can’t be a palindrome
  2. Go through half the array, and find out whether array element is equal to the corresponding element on the “other side”.

    In other words, check whether first element is equal to last element, the second element is equal to the last but one element, and so on.
  3. Repeat (2) until you hit the end (in which case given array is palindrome), or hit an element pair that is not equal (not a palindrome)
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things