Unique pairs in array that forms palindrome words in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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 ] ]
raja
Published on 19-Apr-2021 11:17:08
Advertisements