
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
Unique Pairs in Array That Form Palindrome Words in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of unique words.
Our function should return an array of all such index pairs, the words at which, when combined yield a palindrome word.
Example
Following is the code −
const arr = ["abcd", "dcba", "lls", "s", "sssll"]; const findPairs = (arr = []) => { const res = []; for ( let i = 0; i < arr.length; i++ ){ for ( let j = 0; j < arr.length; j++ ){ if (i !== j ) { let k = `${arr[i]}${arr[j]}`; let l = [...k].reverse().join(''); if (k === l) res.push( [i, j] ); } }; }; return res; }; console.log(findPairs(arr));
Output
[ [ 0, 1 ], [ 1, 0 ], [ 2, 4 ], [ 3, 2 ] ]
Advertisements