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

Ký tự xuất hiện nhiều thứ hai trong chuỗi - JavaScript


Chúng ta cần viết hàm nhận vào chuỗi và trả về ký tự xuất hiện nhiều thứ hai.

Ví dụ chuỗi:

const str = 'This string will be used to calculate frequency';

Ký tự xuất hiện nhiều thứ hai là "e".

Ví dụ

Dưới đây là code hoàn chỉnh:

const str = 'This string will be used to calculate frequency'; 
const secondMostFrequent = str => { 
  const strArr = str.split(''); 
  const map = strArr.reduce((acc, val) => { 
    if(acc.has(val)){ 
      acc.set(val, acc.get(val) + 1); 
    }else{ 
      acc.set(val, 1); 
    }; 
    return acc; 
  }, new Map); 
  const frequencyArray = Array.from(map); 
  return frequencyArray.sort((a, b) => { 
    return b[1] - a[1]; 
  })[1][0]; 
}; 
console.log(secondMostFrequent(str));

Kết quả

Đoạn code sẽ in ra console:

e