将字符串的唯一字符映射到数组-JavaScript

我们需要编写一个JavaScript函数,该函数接受一个字符串并从0开始映射它的字符。每当该函数遇到一个唯一(非重复)字符时,它应将映射计数增加1,否则将相同的数字映射为重复字符。

例如-如果字符串是-

const str = 'heeeyyyy';

那么输出应该是-

const output = [0, 1, 1, 1, 2, 2, 2, 2];

示例

以下是代码-

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
]