

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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. And 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];
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));
Output
Following is the output in the console −
[ 0, 1, 1, 1, 2, 2, 2, 2 ]
- Related Questions & Answers
- Constructing array from string unique characters in JavaScript
- Filtering string to contain unique characters in JavaScript
- Finding unique string in an array in JavaScript
- Mapping the letter of a string to an object of arrays - JavaScript
- Number of non-unique characters in a string in JavaScript
- Mapping string to Numerals in JavaScript
- Finding the only unique string in an array using JavaScript
- Mapping an array to a new array with default values in JavaScript
- Mapping array of numbers to an object with corresponding char codes in JavaScript
- Checking if a string contains all unique characters using JavaScript
- Find unique and biggest string values from an array in JavaScript
- Summing all the unique values of an array - JavaScript
- JavaScript: Computing the average of an array after mapping each element to a value
- Extract unique values from an array - JavaScript
- Reverse mapping an object in JavaScript
Advertisements