เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของค่าคงที่ ฟังก์ชันควรเลือกค่าทั้งหมดที่ปรากฏในอาร์เรย์ครบสองครั้งพอดี และคืนค่าอาร์เรย์ใหม่ขององค์ประกอบเหล่านั้น
ตัวอย่างโค้ด
โค้ดสำหรับการทำงานนี้จะเป็นดังนี้
const arr = [0, 1, 2, 2, 3, 3, 5];
const findAppearances = (arr, num) => {
let count = 0;
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(num !== el){
continue;
};
count++;
};
return count;
};
const pickAppearingTwice = (arr = []) => {
const res = [];
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(findAppearances(arr, el) === 2 && !res.includes(el)){
res.push(el);
};
};
return res;
};
console.log(pickAppearingTwice(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
[2, 3]