Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Mapping unique characters of string to an array - JavaScript
We are required to write a JavaScript function that takes in a string and starts mapping its characters from 0. Every time the function encounters a unique (non-duplicate) character, it should increase the mapping count by 1, otherwise 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];
How It Works
The algorithm works by tracking consecutive character groups. When a character differs from the previous one, we increment the mapping counter. Characters that are the same as the previous character get the same mapping number.
Example
Following is the code:
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));
[
0, 1, 1, 1,
2, 2, 2, 2
]
Step-by-Step Breakdown
Let's trace through the string 'heeeyyyy':
const traceMapping = str => {
const res = [];
let curr = '', count = -1;
for(let i = 0; i < str.length; i++){
if(str[i] === curr){
res.push(count);
console.log(`Position ${i}: '${str[i]}' same as previous, mapped to ${count}`);
}else{
count++;
res.push(count);
curr = str[i];
console.log(`Position ${i}: '${str[i]}' new character, mapped to ${count}`);
}
}
return res;
};
traceMapping('heeeyyyy');
Position 0: 'h' new character, mapped to 0 Position 1: 'e' new character, mapped to 1 Position 2: 'e' same as previous, mapped to 1 Position 3: 'e' same as previous, mapped to 1 Position 4: 'y' new character, mapped to 2 Position 5: 'y' same as previous, mapped to 2 Position 6: 'y' same as previous, mapped to 2 Position 7: 'y' same as previous, mapped to 2
Alternative Implementation
Here's a more concise version using array methods:
const mapStringAlternative = str => {
let count = 0;
return [...str].map((char, i) => {
if (i === 0 || char !== str[i - 1]) {
return count++;
}
return count - 1;
});
};
console.log(mapStringAlternative('heeeyyyy'));
console.log(mapStringAlternative('abcabc'));
[ 0, 1, 1, 1, 2, 2, 2, 2 ] [ 0, 1, 2, 3, 4, 5 ]
Conclusion
This function maps consecutive identical characters to the same number while incrementing the mapping for each new character group. It's useful for grouping consecutive duplicate characters in strings.
