- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
- Related Articles
- Mapping unique characters of string to an array - JavaScript
- Filtering string to contain unique characters in JavaScript
- Constructing largest number from an array in JavaScript
- Constructing an object from repetitive numeral string in JavaScript
- Number of non-unique characters in a string in JavaScript
- Find unique and biggest string values from an array in JavaScript
- Constructing product array in JavaScript
- How to find unique characters of a string in JavaScript?
- Constructing multiples array - JavaScript
- Finding unique string in an array in JavaScript
- Checking if a string contains all unique characters using JavaScript
- Constructing a string based on character matrix and number array in JavaScript
- Omitting false values while constructing string in JavaScript
- Extract unique values from an array - JavaScript
- Removing first k characters from string in JavaScript

Advertisements