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

ค่าที่พบมากที่สุดในอาร์เรย์ หรือค่าแรกที่เลือกใน JavaScript


เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของค่าคงที่ ฟังก์ชันของเราควรคืนค่าความถี่สูงสุดของค่าอาร์เรย์ และถ้ามีความถี่เท่ากัน เราควรคืนค่าที่ถูกเลือกก่อนของความถี่ที่เท่ากัน

const arr = ['25', '50', 'a', 'a', 'b', 'c']

ในกรณีนี้ เราควรคืนค่า 'a'

const arr = ['75', '100', 'a', 'b', 'b', 'a']

ในกรณีนี้ เราควรได้ 'a' เช่นกัน

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

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

const arr = ['25', '50', 'a', 'a', 'b', 'c']; const arr1 = ['75', '100', 'a', 'b', 'b', 'a']; 
const getMostFrequentValue = (arr = []) => { 
  let count = 0, ind = -1; 
  arr.forEach((el, i) => { 
    this[el] = this[el] || { count: 0, ind: i }; 
    this[el].count++; 
    if (this[el].count > count) { 
      count = this[el].count; 
      ind = this[el].ind; 
      return; 
    }; 
    if (this[el].count === count && this[el].ind < ind) { 
      ind = this[el].ind; 
    }; 
  }, Object.create(null)); 
  return arr[ind]; 
}; 
console.log(getMostFrequentValue(arr)); 
console.log(getMostFrequentValue(arr1));

ผลลัพธ์

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

a a