

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding the only unique string in an array using JavaScript
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 −
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
- Related Questions & Answers
- Finding unique string in an array in JavaScript
- Finding the only out of sequence number from an array using JavaScript
- Finding the longest string in an array in JavaScript
- Finding the sum of unique array values - JavaScript
- Finding Fibonacci sequence in an array using JavaScript
- Finding first unique element in sorted array in JavaScript
- Finding the first unique element in a sorted array in JavaScript
- Mapping unique characters of string to an array - JavaScript
- Finding all the unique paths in JavaScript
- Finding product of an array using recursion in JavaScript
- Finding the most frequent word(s) in an array using JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript
- Find unique and biggest string values from an array in JavaScript
- Finding the index position of an array inside an array JavaScript
Advertisements