เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ตัวเลขเป็นอาร์กิวเมนต์เดียว ฟังก์ชันต้องสร้างและคืนอาร์เรย์ใหม่จากอาร์เรย์เดิม อาร์เรย์ใหม่ควรมีสมาชิกทั้งหมดจากอาร์เรย์เดิมที่มีค่าเท่ากับดัชนีที่วางอยู่
สังเกตว่าเราต้องตรวจสอบค่าและดัชนีโดยใช้ 1-based index ไม่ใช่ 0-based index แบบเดิม
ตัวอย่าง
ถ้าอาร์เรย์นำเข้าคือ:
const arr = [45, 5, 2, 4, 6, 6, 6];
ผลลัพธ์ควรเป็น:
const output = [4, 6];
ตัวอย่างโค้ด
const arr = [45, 5, 2, 4, 6, 6, 6];
const pickSameElements = (arr = []) => {
const res = [];
const { length } = arr;
for(let ind = 0; ind < length; ind++) {
const el = arr[ind];
if(el - ind === 1) {
res.push(el);
}
}
return res;
};
console.log(pickSameElements(arr));
ผลลัพธ์
[4, 6]