हमें एरे के लिए एक फ़ंक्शन लिखना आवश्यक है Array.prototype.remove()। यह एक आर्गुमेंट स्वीकार करता है; यह या तो एक कॉलबैक फ़ंक्शन है या एरे का एक संभावित तत्व। यदि यह एक फ़ंक्शन है तो उस फ़ंक्शन का रिटर्न मान एरे के संभावित तत्व के रूप में माना जाना चाहिए और हमें उस तत्व को एरे में ढूंढना और हटाना है इन-प्लेस और फ़ंक्शन को 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' } ]