
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Checking for Special Type of Arrays in 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. 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
Advertisements