เราจำเป็นต้องเขียนฟังก์ชัน 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' ]