Tìm ký tự xuất hiện nhiều thứ hai trong JavaScript
Chúng ta cần viết một hàm JavaScript nhận vào một chuỗi và trả về ký tự xuất hiện nhiều thứ hai trong chuỗi.
Do đó, hãy viết mã cho hàm này:
Ví dụ
Mã thực hiện như sau:
const str = 'Hello world, I have never seen such a beautiful weather in the world';
const secondFrequent = str => {
const map = {};
for(let i = 0; i < str.length; i++){
map[str[i]] = (map[str[i]] || 0) + 1;
};
const freqArr = Object.keys(map).map(el => [el, map[el]]);
freqArr.sort((a, b) => b[1] - a[1]);
return freqArr[1][0];
};
console.log(secondFrequent(str));
Đầu ra
Kết quả trong console sẽ là:
e