Constructing array from string unique characters in JavaScript

We are required to write a JavaScript function that takes in a string and starts mapping its characters from 0.

And every time, the function encounters a unique (non-duplicate) character it should increase the mapping count by 1 otherwise it should map the same number for duplicate characters.

For example: If the string is ?

const str = 'heeeyyyy';

Then the output should be ?

const output = [0, 1, 1, 1, 2, 2, 2, 2];

Therefore, let's write the code for this function ?

Example

The code for this will be ?

const str = 'heeeyyyy';
const mapString = str => {
    const res = [];
    let curr = '', count = -1;
    for(let i = 0; i < str.length; i++){
        if(str[i] === curr){
            res.push(count);
        }else{
            count++;
            res.push(count);
            curr = str[i];
        };
    };
    return res;
};
console.log(mapString(str));

Output

The output in the console will be ?

[
    0, 1, 1, 1,
    2, 2, 2, 2
]

How It Works

The function works by tracking the current character and incrementing a counter only when a new unique character is encountered:

  • h: First unique character ? count becomes 0
  • e: Second unique character ? count becomes 1
  • e, e: Duplicate characters ? same count (1)
  • y: Third unique character ? count becomes 2
  • y, y, y: Duplicate characters ? same count (2)

Alternative Approach Using Map

Here's another implementation using a Map to track character mappings:

const str = 'heeeyyyy';
const mapStringWithMap = str => {
    const charMap = new Map();
    const result = [];
    let uniqueCount = 0;
    
    for(let char of str) {
        if(!charMap.has(char)) {
            charMap.set(char, uniqueCount);
            uniqueCount++;
        }
        result.push(charMap.get(char));
    }
    
    return result;
};

console.log(mapStringWithMap(str));
[
    0, 1, 1, 1,
    2, 2, 2, 2
]

Conclusion

This technique creates a unique character mapping by assigning incremental numbers to each new character encountered. Both approaches achieve the same result, with the Map version offering cleaner character tracking.

Updated on: 2026-03-15T23:19:00+05:30

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements