ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลข arr เป็นอาร์กิวเมนต์เดียว
อาร์เรย์ arr อาจมีค่าซ้ำ ฟังก์ชันควรเรียงอาร์เรย์ให้สมาชิกที่ปรากฏน้อยที่สุดอยู่หน้า ตามด้วยความถี่มากขึ้น
ถ้าสองสมาชิกปรากฏเท่ากัน ให้เรียงจากน้อยไปมาก
ตัวอย่างเช่น หากอินพุตคือ
Input
const arr = [5, 4, 5, 4, 2, 1, 12];
Output
const output = [1, 2, 12, 4, 4, 5, 5];
คำอธิบายผลลัพธ์
ตัวเลข 1, 2, 12 ปรากฏครั้งละ 1 จึงเรียงน้อยไปมาก แล้ว 4 และ 5 ปรากฏครั้งละ 2
ตัวอย่าง
โค้ดด้านล่างนี้
const arr = [5, 4, 5, 4, 2, 1, 12];
const sortByAppearance = (arr = []) => {
arr.sort((a, b) => a - b);
const res = [];
const searched = {};
const countAppearance = (list, target) => {
searched[target] = true;
let count = 0;
let index = list.indexOf(target);
while(index !== -1){
count++;
list.splice(index, 1);
index = list.indexOf(target);
}
return count;
};
const map = [];
arr.forEach(el => {
if(!searched.hasOwnProperty(el)){
map.push([el, countAppearance(arr.slice(), el)]);
}
});
map.sort((a, b) => a[1] - b[1]);
map.forEach(([num, freq]) => {
while(freq){
res.push(num);
freq--;
}
});
return res;
};
console.log(sortByAppearance(arr));ผลลัพธ์
[1, 2, 12, 4, 4, 5, 5]