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

การหาค่าที่พบบ่อยที่สุดในอาร์เรย์ด้วย JavaScript

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของค่าคงที่ซึ่งมีค่าซ้ำกัน ฟังก์ชันควรคืนอาร์เรย์ขององค์ประกอบที่พบบ่อยที่สุด (ถ้ามีสององค์ประกอบขึ้นไปที่ปรากฏบ่อยเท่ากัน ให้รวมทั้งหมดในอาร์เรย์ผลลัพธ์)

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

const arr1 = ["a", "c", "a", "b", "d", "e", "f"];
const arr2 = ["a", "c", "a", "c", "d", "e", "f"];
const getMostCommon = arr => {
  const count = {};
  let res = [];
  arr.forEach(el => {
    count[el] = (count[el] || 0) + 1;
  });
  res = Object.keys(count).reduce((acc, val, ind) => {
    if (!ind || count[val] > count[acc[0]]) {
      return [val];
    };
    if (count[val] === count[acc[0]]) {
      acc.push(val);
    };
    return acc;
  }, []);
  return res;
}
console.log(getMostCommon(arr1));
console.log(getMostCommon(arr2));

ผลลัพธ์

ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:

[ 'a' ] [ 'a', 'c' ]