I am trying to make a function in my js file that will remove an item from an array and then save the new array to the variable. But here’s the thing: I don’t want it to only save ONE variable, I want it to save any array variable that I input. What I mean is something like this:
const list = [1,2,3]; function removeItem(array,index) { let newArray = []; for(var i = 0 ; i < array.length ; i++) { if(i != index) { newArray.push(array[i]); } } array = newArray; // where it saves the variable } removeItem(list,0);
Advertisement
Answer
You can create a prototype function, see this
Array.prototype.removeItem = function(what) { if (this.indexOf(what) >= 0) this.splice(this.indexOf(what), 1); } var foo = [1, 2, 3]; foo.removeItem(2); console.log(foo);