Duplicate Javascript Counter Letter

I'm a new student here, sorry to ask a simple question, and I'm trying to solve a problem in order to count the same letter.

Input:"aabbcde"
cause a = 2, b= 2, c= 1 , d =1 , e = 1
Output:"2a2b1c1d1e" or a2b2c1d1e1

and here my code is not finished i'm stuck

function repeatL(str) {
    var word = str.split("").sort();
    var temp = 0;
    var i =1;
    while(i< word.length){
        if(word[i] === word[i +1]) { 
            //return temp to array of a += 1 ?
        };
    }
}
repeatL("abbbdd"); //output should be a1b3d2

also, if the input is not a string, but an array:

Input:[a,ab,bc,d,e]

what can even be solved?

+4
source share
4 answers

You can use a variable for the result string, start with the variable count from 1 and iterate over to check the first and actual letters. Then either count or move the counter to the result set with the last letter. Reset occurs with one, because the actual number of letters is one.

, (, 1, ).

function repeatL(str) {
    var word = str.split("").sort(),
        count = 1,
        i = 1,
        result = '';

    while (i < word.length) {
        if (word[i - 1] === word[i]) {
            count++;
        } else {
            result += count + word[i - 1];
            count = 1;
        }
        i++;
    }
    result += count + word[i - 1];
    return result;
}

console.log(repeatL("aabbcde"));
console.log(repeatL(['a', 'ab', 'bc', 'd', 'e'].join(''))); // with array after joining
Hide result
+4

reduce() , join() .

var input = "aabbcde";

var result = input.split('').reduce(function(r, e) {
  var i = r.indexOf(e);
  (i != -1) ? r[i - 1] ++: r.push(1, e)
  return r;
}, []).join('')

console.log(result)
Hide result
0

I would go with the object and add each character as a key. If the key exists, increase the value, otherwise add a new key and with the value 1

function repeatL(str) {
  var count = {};
  var arr = str.split("");
    str = "";
  for(var i=0;i<arr.length;i++){
    if(count[arr[i]]){
      count[arr[i]] = count[arr[i]]+1;
    }
    else {
       count[arr[i]] = 1;
    }
  }
  for(var key in count){
    str+= key+count[key];
  }
  return str;
}
0
source

The following example also works with arrays:

function getFrequency(string) {
    var freq = {};
    for (var i=0; i<string.length;i++) {
        var character = string[i];
        if (freq[character]) {
          freq[character]++;
        } else {
          freq[character] = 1;
        }
    }

    return freq;
};

function repeatL(str) {
    var freq = getFrequency(str);
    result = '';
    for (var k in freq) {
        if (freq.hasOwnProperty(k)) {
          result += freq[k] + k;
        }
    }
    return result;
};

console.log(repeatL('abbbdd'));
console.log(repeatL('aabbcdeaaabbeedd'));
console.log(repeatL(['a', 'a', 'b', 'a', 'c']));
Run codeHide result
0
source

Source: https://habr.com/ru/post/1661561/


All Articles