Finding the only unique string in an array using JavaScript


Unraveling the enigma of finding the solitary unique string within an array using JavaScript holds paramount importance for developers seeking to optimize their code. With the ability to handle complex data structures, JavaScript empowers programmers to solve intricate problems efficiently. In this article, we delve into the intricacies of identifying the lone unique string amidst an array, employing an arsenal of rarely used but indispensable techniques. By mastering the step-by-step approach presented herein, developers will acquire the prowess to sift through arrays, discerning the one string that stands distinct from the rest. Brace yourself for a journey into the depths of JavaScript's linguistic arsenal as we unlock the secrets of extracting the only unique string within an array.

Problem Statement

Write a JavaScript function that takes an array of strings as input and returns the only unique string present in the array. A unique string is defined as a string that occurs only once in the given array. If there are no unique strings, the function should return null.

Sample Input −

const strings = ["apple", "banana", "orange", "banana", "kiwi", "kiwi", "apple"];

Sample Output −

orange

In the given sample input, the string "orange" occurs only once in the array, making it the unique string. Therefore, the function should return "orange" as the output.

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Naïve Approach

  • Using HashMap

Method 1: Naïve Approach

To find the only unique string in an array using a naive approach in JavaScript, first define the array named stringArray. Create the findUniqueString() function, which iterates through each string in the array using a loop. Within the loop, compare each string with every other string using a nested loop. If a duplicate is found, set the isDuplicate flag to true. After the nested loop, check the isDuplicate flag for the current string. If it remains false, consider the string as the unique string. Finally, return the unique string from the findUniqueString() function.

Example

The "findUniqueString" function searches for the first non-duplicate string in an array using nested loops. The outer loop iterates over each element, while the inner loop compares the current string with every other string. If a match is found, the "unique" variable is set to false. If no duplicates are found, the unique string is returned. If the outer loop completes without finding a unique string, null is returned. The example usage of the function with the "strings" array assigns the result to "uniqueString" and logs it to the console.

function findUniqueString(arr) {
   for (let i = 0; i < arr.length; i++) {
      let unique = true;
      for (let j = 0; j < arr.length; j++) {
         if (i !== j && arr[i] === arr[j]) {
            unique = false;
            break;
         }
      }
      if (unique) {
         return arr[i];
      }
   }
   return null; // If no unique string is found
}

// Example usage
const strings = ["apple", "banana", "apple", "banana", "orange"];
const uniqueString = findUniqueString(strings);
console.log(uniqueString);

Output

The following is the console output −

orange

Method 2: Using HashMap

To find the only unique string in an array using JavaScript and a hashmap data structure, first define the stringArray. Create an empty hashmap called stringCountMap. Iterate over each element in stringArray and check if it exists as a key in stringCountMap. If not, add it with a count of 1; otherwise, increment its count. After iterating, we have a hashmap with each string and its occurrence count. Finally, iterate over the hashmap's keys and check if the count is 1. If so, that string is the unique one in stringArray.

Example

The findUniqueString function receives an array as input and searches for a string that occurs only once within the array. It maintains a countMap variable to track the count of each encountered string. By iterating through the array, the code updates the count for existing strings and creates new key-value pairs for new strings. Upon completion, it checks the countMap for a key with a count of 1 and returns the unique string if found. If no unique string is found, it returns null. An example demonstrates the function's usage by calling it with an array of strings and printing the resulting unique string to the console.

function findUniqueString(arr) {
   const countMap = {};
   for (let i = 0; i < arr.length; i++) {
      const str = arr[i];
      countMap[str] = (countMap[str] || 0) + 1;
   }
   for (const key in countMap) {
      if (countMap[key] === 1) {
         return key;
      }
   }
   return null; // If no unique string is found
}

// Example usage
const strings = ["apple", "banana", "apple", "banana", "orange"];
const uniqueString = findUniqueString(strings);
console.log(uniqueString);

Output

The following is the console output −

orange

Conclusion

In conclusion, unearthing the singularly distinctive string within an array using JavaScript can be a perplexing endeavor, requiring meticulous scrutiny and astute algorithmic design. However, employing the appropriate approach, such as leveraging efficient data structures and employing esoteric techniques, can bestow upon us the ability to unravel this enigmatic conundrum. By delving into the intricacies of the problem at hand and harnessing the power of uncommon methodologies, we can triumphantly extract the elusive gem from the sea of redundancy. In essence, the pursuit of identifying the solitary idiosyncratic string within an array demands a tenacious spirit and an unwavering commitment to unraveling the cryptic depths of the coding realm.

Updated on: 04-Aug-2023

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements