Finding the only unique string in an array using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of strings. All the strings in the array contain the same characters, or the repetition of characters, and just one string contains a different set of characters. Our function should find and return that string.

For example

If the array is −

[‘ba’, 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]

Then the required string is ‘foo’.

Strings may contain spaces. Spaces are not significant, only non-spaces symbols matter. Example, a string that contains only spaces is like an empty string. It’s guaranteed that the array contains more than 3 strings.

Example

Following is the code −

 Live Demo

const arr = ['ba', 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ];
const findOnlyUnique = (arr = []) => {
   const first = [];
   for(i = 0; i < arr.length; i++){
      first.push(arr[i].toLowerCase().replace(/\s/g, '').split(''));
      for (j = 0; j < arr[i].length; j++){
         first[i].sort();
      }
   }
   const second = [];
   for (k = 0; k < arr.length; k++){
      second.push(first[k].join());
   }
   second.sort();
   const third = [];
   if (second[1] !== second[second.length - 1]) {
      third.push(second[second.length - 1]);
   }else{
      third.push(second[0]);
   }
   const last = [];
   for(let n = 0; n < first.length; n++){
      last.push(first[n].join(','));
   }
   return (arr[last.indexOf(third[0])]);
};
console.log(findOnlyUnique(arr));

Output

foo
raja
Published on 20-Apr-2021 09:10:41
Advertisements