다음과 같이 공백으로 구분된 일부 문자를 포함하는 문자열이 있다고 가정합니다. −
const str = 'a b c d a v d e f g q';
우리는 그러한 문자열 하나를 취하는 JavaScript 함수를 작성해야 합니다. 함수는 문자와 개수를 포함하는 개체의 빈도 배열을 준비해야 합니다.
예시
이에 대한 코드는 -
const str = 'a b c d a v d e f g q';
const countFrequency = (str = '') => {
const result = [];
const hash = {};
const words = str.split(" ");
words.forEach(function (word) {
word = word.toLowerCase();
if (word !== "") {
if (!hash[word]) {
hash[word] = { name: word, count: 0 };
result.push(hash[word]);
};
hash[word].count++;
};
});
return result.sort((a, b) => b.count − a.count)
}
console.log(countFrequency(str)); 출력
콘솔의 출력은 -
[
{ name: 'a', count: 2 },
{ name: 'd', count: 2 },
{ name: 'b', count: 1 },
{ name: 'c', count: 1 },
{ name: 'v', count: 1 },
{ name: 'e', count: 1 },
{ name: 'f', count: 1 },
{ name: 'g', count: 1 },
{ name: 'q', count: 1 }
]