[05.03.22] Coding test

Juyeon.it·2022년 5월 3일
0

Coding test

목록 보기
22/32

Count characters in your string

Description

The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.
What if the string is empty? Then the result should be empty object literal, {}.

My answer

function count (string) {  
  let result = {};
  
  for(let i = 0; i < string.split('').length; i++) {
    let count = string.split('').filter(a => a === string.split('')[i]).length;
    result[string.split('')[i]] = count;
  }
  
   return result;
}

Other solutions

function count (string) {  
  var count = {};
  string.split('').forEach(function(s) {
     count[s] ? count[s]++ : count[s] = 1;
  });
  return count;
}
function count (string) {
  var result = {};
  
  for(let i = 0; i < string.length; i++) {
    if(result.hasOwnProperty(string[i])){
      result[string[i]] += 1;
    } else {
      result[string[i]] = 1;
    }
  }
  
  return result;
}

0개의 댓글

관련 채용 정보