Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tìm ký tự xuất hiện nhiều thứ 2 trong chuỗi - JavaScript

Viết hàm nhận chuỗi, trả về ký tự có tần suất xuất hiện nhiều thứ 2 (kể cả khoảng trắng).

Ví dụ

Chuỗi: 'Hello world, I have never seen such a beautiful weather in the world'

Giải pháp

Mã triển khai:

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;
  }
  // Chuyển thành mảng [char, count] và sắp xếp giảm dần
  const freqArr = Object.entries(map).sort((a, b) => b[1] - a[1]);
  return freqArr[1]?.[0] || ''; // Ký tự rank 2
};

console.log(secondFrequent(str));

Kết quả

Đầu ra trong console:

e

Giải thích: Ký tự ' ' (space) thường nhiều nhất, 'e' đứng thứ 2.