Mapping unique characters of string to an array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
raja
Published on 18-Sep-2020 09:12:26
Advertisements