Checking for Duplicate Strings in JavaScript Array
Last Updated :
03 May, 2024
Checking for duplicate strings in a JavaScript array involves identifying if there are any repeated string values within the array. Given an array of strings a with size N, find all strings that occur more than once. If none is found, return [-1].
Example:
Input:
N = 4
arr = ['apple', 'banana', 'orange', 'apple']
Output :
[ 'apple' ]
Explanation :
There is only 'apple' is repeating 2 times therefore output is 'apple' in given array.
Using Iteration
In this approach, iterate through the array and compare each element with every other element to detect duplicates. This method has a time complexity of O(n^2) as it involves nested iteration over the array, making it less efficient for large datasets.
Example: Implementation to check for duplicate strings in JavaScript array using simple iteration.
JavaScript
function duplicateStr(arr) {
let res = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
res.push(arr[i]);
}
}
}
if (res.length == 0) res.push(-1);
return res;
}
const array = ['apple', 'banana', 'orange', 'apple'];
console.log(duplicateStr(array));
Time complexity: 0( n2 )
Space complexity: 0( 1 )
Using Set
Utilize a Set data structure to store unique elements. While iterating through the array, check if the element already exists in the Set.
Example: Implementation to check for duplicate strings in JavaScript array using set.
JavaScript
function duplicatesStr(arr) {
const set = new Set();
const res = [];
for (let item of arr) {
if (set.has(item)) {
res.push(item);
}
else set.add(item);
}
res.length == -1 && res.push(-1);
return res;
}
const array = ["apple", "orange", "apple", "mango", "banana", "kiwi", "banana"];
console.log(duplicatesStr(array));
Output[ 'apple', 'banana' ]
Time complexity: 0( n )
Space complexity: 0 ( n )
Using Sorting
In the sorting approach, begin by sorting the array. Then, iterate through it and check if adjacent elements are identical. This method offers a time complexity of O(n log n) due to the sorting operation, followed by a linear iteration to identify duplicates, providing an efficient means for duplicate detection in arrays.
Example: Implementation to check for duplicate strings in JavaScript array using sorting method.
JavaScript
function duplicatesStr(arr) {
arr.sort();
const res = [];
for (let i = 0; i < arr.length - 1; i++) {
let flage = false;
while (i < arr.length && arr[i] === arr[i + 1]) {
flage = true;
i++;
}
if (flage) res.push(arr[i]);
}
res.length == 0 && res.push(-1);
return res;
}
const array = ["apple", "banana", "orange",
"apple", "mango", "banana", "kiwi", "banana"];
console.log(duplicatesStr(array));
Output[ 'apple', 'banana' ]
Time complexity: 0(n log n)
Space complexity: 0( 1 )
Frequency counting
In the frequency counting approach, utilize an object to store the frequency of each string in the array. Then, return an array of strings that have a frequency greater than one. This method offers a time complexity of O(n) as it involves a single iteration over the array to count frequencies, providing an efficient solution for identifying duplicate strings.
Example: Implementation to check for duplicate strings in JavaScript array using frequency counting method.
JavaScript
function duplicatesStr(arr) {
const freqMap = {};
for (let item of arr) {
if (item in freqMap) freqMap[item]++;
else freqMap[item] = 1;
}
const res = [];
for (const key in freqMap) {
if (freqMap[key] > 1) res.push(key);
}
if (res.length == 0) res.push(-1);
return res;
}
const array = ["apple", "banana", "orange", "apple",
"mango", "banana", "apple", "banana", "orange",
"apple", "mango", "banana"];
console.log(duplicatesStr(array));
Output[ 'apple', 'banana', 'orange', 'mango' ]
Time complexity: 0( n )
Space complexity: 0 ( n )
Similar Reads
JavaScript Program to Print All Duplicate Characters in a String In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = âgeeksforgeeksâOutput:e, count = 4g, count = 2k, count = 2s, count = 2Ta
5 min read
JavaScript Program to Find Duplicate Elements in an Array Here are the different methods to find duplicate elements in the array1. Using Nested For In LoopThe for...in loop is typically used to iterate over the keys of an object or the indices of an array.JavaScriptconst a = [1, 2, 3, 4, 5, 2, 3, 6]; let dupli = []; for (let i in a) { for (let j in a) { if
4 min read
JavaScript Program to Remove Consecutive Duplicate Characters From a String We are going to implement a JavaScript program to remove consecutive duplicate characters from a string. In this program, we will eliminate all the consecutive occurrences of the same character from a string.Example:Input: string: "geeks" Output: "geks"Explanation :consecutive "e" should be removedT
5 min read
JavaScript Program to Check for Repeated Characters in a String Here are the different methods to check for repeated characters in a string using JavaScript1. Using a Frequency Counter (Object)A frequency counter is one of the most efficient ways to check for repeated characters in a string. This approach involves iterating over the string and counting how often
3 min read
JavaScript Program to Check if an Array is Palindrome or Not A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. To check if an array is a palindrome, compare it to its reverse version. If they match, it's a palindrome. Given an array, the task is to determine whether an array is a palindrome. Exam
3 min read
JavaScript Program to Check if Two Arrays are Equal or Not Given two arrays, arr1 and arr2 of equal length N, the task is to find if the given arrays are equal or not. Two arrays are said to be equal if: Both of them contain the same set of elements, Arrangements (or permutations) of elements might/might not be the same.If there are repetitions, then counts
4 min read
JavaScript Program to Check Equal Character Frequencies We have given a String to ensure it has equal character frequencies, if not, equate by adding required characters and printing the final string in the console.Example:Input: test_str = âgeeksforgeeksâ Output: geeksforgeeksggkkssfffooorrr Explanation: Maximum characters are 4 of âeâ. Other character
6 min read
JavaScript Program to Check if Kth Index Elements are Unique In this article, We have given a String list and a Kth index in which we have to check that each item in a list at that particular index should be unique. If they all are unique then we will print true in the console else we will print false in the console.Example:Input: test_list = [âgfgâ, âbestâ,
6 min read
JavaScript Program to Check if Two Strings are Same or Not In this article, we are going to implement a JavaScript program to check whether two strings are the same or not. If they are the same then we will return true else we will return false.Examples: Input: str1 = Geeks, str2 = GeeksOutput: True. Strings are the SameInput: str1 = Geeks, str2 = GeekOutpu
4 min read
JavaScript Program to find Intersection of Unsorted Arrays JavaScript arrays are versatile structures used to store collections of elements. Oftentimes, these arrays may contain duplicates, and finding the common elements among them, known as the "intersection," becomes necessary. In this article, we'll explore various methods to efficiently find the inters
3 min read