
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- Constructing array from string unique characters in JavaScript
- Filtering string to contain unique characters in JavaScript
- How to find unique characters of a string in JavaScript?
- Finding unique string in an array in JavaScript
- Number of non-unique characters in a string in JavaScript
- Mapping the letter of a string to an object of arrays - 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
- Checking if a string contains all unique characters using JavaScript
- Find unique and biggest string values from an array in JavaScript
- Mapping array of numbers to an object with corresponding char codes in JavaScript
- JavaScript: Computing the average of an array after mapping each element to a value
- Extract unique values from an array - JavaScript
- Summing all the unique values of an array - JavaScript

Advertisements