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
Finding unique string in an array in JavaScript
Suppose, we have the following array of strings that might contain duplicate characters −
const arr = ['54gdgdfe3', '434ffd', '43frdf', '43fdhnh', 'wgcxhjny', 'fsdf34'];
We are required to write a JavaScript function that takes in one such array and returns the very first element from the array that contains 0 duplicate characters.
If there does not exist any such string, we should return false.
Example
Following is the code −
const arr = ['54gdgdfe3', '434ffd', '43frdf', '43fdhnh', 'wgcxhjny',
'fsdf34'];
const isUnique = str => {
return str.split('').every(el => str.indexOf(el) ===
str.lastIndexOf(el));
};
const findUniqueString = arr => {
for(let i = 0; i < arr.length; i++){
if(isUnique(arr[i])){
return arr[i];
};
};
return false;
};
console.log(findUniqueString(arr));
Output
Following is the output in the console −
wgcxhjny
Advertisements