How to use Set and Array Filter In Javascript
In this approach, we can utilize a Set data structure to keep track of unique characters at the Kth index of each string in the given list. We iterate through the list, extract the character at the Kth index of each string, and add it to the Set. If any character is already present in the Set, it indicates that there is a duplicate, and we return false. Otherwise, we return true if all characters are unique.
Example:
// Initialize the list
let test_list = ["gfg", "best", "for", "geeks"];
// Print the original list
console.log("The original list is: " + test_list);
// Initialize K
let K = 2;
// Use Set to store unique characters
let charSet = new Set();
// Iterate through the list and check for uniqueness
let isUnique = test_list.every((str) => {
let char = str.charAt(K);
if (charSet.has(char)) {
return false; // If character is already present, return false
} else {
charSet.add(char); // Add character to Set
return true;
}
});
// Print the result
console.log("Is Kth index all unique: " + isUnique);
Output
The original list is: gfg,best,for,geeks Is Kth index all unique: true
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”, “for”, “geeks”], K = 1 .
Output: False
Explanation: e occurs as 1st index in both best and geeks.
Input: test_list = [“gfg”, “best”, “geeks”], K = 2
Output: True
Explanation: g, s, e, all are unique.
These are the following approaches by using these we can solve this question:
Table of Content
- Using for loop:
- Using every() method
- Using Set and Array Filter
Contact Us