Open In App

JavaScript Program to Check if Kth Index Elements are Unique

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

In this approach, we iterate for each string and check whether the character is present in the empty array or not. if the character is present in the ‘res’ array it means the value is not unique and it will return false else it will iterate the whole array check for the unique array and return true.

Example: This example shows the use of the above-explained approach.

Javascript




// Initializing list
let test_list = ["gfg", "best", "for", "geeks"];
 
// Printing original list
console.log("The original list is : " + test_list);
 
// Initializing K
let K = 2;
 
let res = [];
let flag = true;
for (let i = 0; i < test_list.length; i++) {
    let ele = test_list[i];
 
    // Checking if element is repeated
    if (res.includes(ele.charAt(K))) {
        flag = false;
        break;
    } else {
        res.push(ele.charAt(K));
    }
}
 
// Printing result
console.log("Is Kth index all unique : " + flag);


Output

The original list is : gfg,best,for,geeks
Is Kth index all unique : true

Using every() method

In this approach, we are checking if the characters at the 2nd index in the array test_list are unique. It initializes a count object to store character occurrences, then checks if all counts are less than 2 using every(). It prints “Is Kth index all unique : true” if all characters are unique, and “Is Kth index all unique : false” otherwise.

Example: This example shows the use of the above-explained approach.

Javascript




// Initializing list
let test_list = ["gfg", "best", "for", "geeks"];
 
// Printing original list
console.log("The original list is : " + test_list);
 
// Initializing K
let K = 2;
 
// Getting count of each Kth index item
let count = {};
for (let i = 0; i < test_list.length; i++) {
    let sub = test_list[i];
    let char = sub.charAt(K);
    count[char] = (count[char] || 0) + 1;
}
 
// Extracting result
let res = Object.values(count).every((val) => val < 2);
 
// Printing result
console.log("Is Kth index all unique : " + res);


Output

The original list is : gfg,best,for,geeks
Is Kth index all unique : true


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads