เราต้องเขียนฟังก์ชันสำหรับอาร์เรย์ Array.prototype.remove() มันรับอาร์กิวเมนต์หนึ่ง คือฟังก์ชัน callback หรือองค์ประกอบที่เป็นไปได้ของอาร์เรย์ ถ้าเป็นฟังก์ชัน ค่าคืนของฟังก์ชันนั้นควรถูกพิจารณาว่าเป็นองค์ประกอบที่เป็นไปได้ของอาร์เรย์ และเราต้องหาและลบองค์ประกอบนั้นออกจากอาร์เรย์แบบ in-place และฟังก์ชันควรคืนค่า true ถ้าพบและลบองค์ประกอบนั้น มิฉะนั้นคืนค่า false
ดังนั้น มาเขียนโค้ดสำหรับฟังก์ชันนี้
ตัวอย่าง
const arr = [12, 45, 78, 54, 1, 89, 67]; const names = [{ fName: 'Aashish', lName: 'Mehta' }, { fName: 'Vivek', lName: 'Chaurasia' }, { fName: 'Rahul', lName: 'Dev' }]; const remove = function(val){ let index; if(typeof val === 'function'){ index = this.findIndex(val); }else{ index = this.indexOf(val); }; if(index === -1){ return false; }; return !!this.splice(index, 1)[0]; }; Array.prototype.remove = remove; console.log(arr.remove(54)); console.log(arr); console.log(names.remove((el) => el.fName === 'Vivek')); console.log(names);ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
true [ 12, 45, 78, 1, 89, 67 ] true [ { fName: 'Aashish', lName: 'Mehta' }, { fName: 'Rahul', lName: 'Dev' } ]