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