Javascript Array removeElement(element)
Array.prototype.removeElement = function(element) { var idx = this.indexOf(element); if (idx <= (-1)) { return;//w ww . ja v a 2 s .c o m } return this.remove(idx); }; Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); };
//Write a function that removes all elements with a given value. //? Attach it to the array type. //?Read about prototype and how to attach methods. // var arr = [1,2,1,4,1,3,4,1,111,3,2,1,'1']; // arr.remove(1); //arr = [2,4,3,4,111,3,2,'1']; var arr = [1,2,1,4,1,3,4,1,111,3,2,1,'1']; Array.prototype.removeElement = function removeElement(element){ for (var i = 0; i < arr.length; i+=1) { if(arr[i]===element){ arr.splice(i,1)//from w w w .java 2 s . c o m } } return arr; }; console.log(arr.removeElement(1));
/*// w w w.j av a 2s . c o m Problem 2. Remove elements Write a function that removes all elements with a given value. Attach it to the array type. Read about prototype and how to attach methods. var arr = [1,2,1,4,1,3,4,1,111,3,2,1,'1']; arr.remove(1); //arr = [2,4,3,4,111,3,2,'1']; */ Array.prototype.removeElement = function (element){ var output = []; for (var index = 0; index < this.length; index+=1) { if (this[index]!==element) { output.push(this[index]); } } return output; }; var inputArray = [1,2,1,4,1,3,4,1,111,3,2,1,'1']; console.log('Initial array: '+inputArray); inputArray = inputArray.removeElement(1); console.log('Initial array w/o number 1: '+inputArray);