เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของค่าต่างๆ เข้ามา ฟังก์ชันจะนับความถี่ของแต่ละสมาชิกในอาร์เรย์อินพุต แล้วสร้างอาร์เรย์ใหม่ตามฐานข้อมูลนั้น
เช่น ถ้าอาร์เรย์อินพุตคือ:
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
ผลลัพธ์ควรเป็น:
const output = [ [5, 3], [2, 5], [9, 1], [4, 1] ];
ตัวอย่างโค้ด
โค้ดสำหรับทำสิ่งนี้คือ:
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const frequencyArray = (arr = []) => {
const res = [];
arr.forEach(el => {
if (!this[el]) {
this[el] = [el, 0];
res.push(this[el])
};
this[el][1]++
}, {});
return res;
};
console.log(frequencyArray(arr));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]