How to use Array.every() Method In Javascript
In this approach, we utilize the Array.every() method to check if the array is a palindrome. We compare each element of the array with its corresponding element from the reverse side of the array. If all the elements match, the array is a palindrome; otherwise, it’s not.
Example:
function isPalindrome(arr) {
return arr.every((element, index) => element === arr[arr.length - 1 - index]);
}
const array1 = [1, 2, 3, 2, 1];
const array2 = [1, 2, 3, 4, 5];
console.log(isPalindrome(array1) ? 'Palindrome' : 'Not Palindrome');
console.log(isPalindrome(array2) ? 'Palindrome' : 'Not Palindrome');
Output
Palindrome Not Palindrome
JavaScript Program to Check if an Array is Palindrome or Not
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. To check if an array is a palindrome, compare it to its reverse version. If they match, it’s a palindrome.
Given an array, the task is to determine whether an array is a palindrome.
Examples:
Input: arr = [3, 6, 0, 6, 3]
Output: Palindrome
Input: arr = [1, 2, 3, 4, 5]
Output: Not Palindrome
Below are the approaches to checking if an array is palindrome or not.
Table of Content
- Using Array Reversal
- Using Iteration
- Using two pointer
- Using Array.every() Method: