Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาตัวอักษรที่มีความถี่อันดับ 2 ในสตริง - JavaScript

ฟังก์ชันนี้หาตัวอักษรที่ปรากฏบ่อยเป็นอันดับ 2 ในสตริง (รวมช่องว่างและสัญลักษณ์)

ตัวอย่าง

// Input: 'Hello world, I have never seen such a beautiful weather in the world'
// Output: 'e'

ตัวอย่างโค้ด

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;
  }

  // แปลงเป็นอาร์เรย์ [[char, count], ...] และเรียงมากไปน้อย
  const freqArr = Object.keys(map).map(el => [el, map[el]]);
  freqArr.sort((a, b) => b[1] - a[1]);

  return freqArr[1][0]; // index 1 = อันดับ 2
};

console.log(secondFrequent(str));

การทำงาน

  1. นับความถี่แต่ละตัวอักษรด้วย object
  2. แปลงเป็นอาร์เรย์คู่ [char, count]
  3. เรียงลำดับ count มากไปน้อย
  4. คืนตัวอักษร index 1

ผลลัพธ์

e