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:
JavaScript
x
17
17
1
const list = [1,2,3];
2
3
function removeItem(array,index)
4
{
5
let newArray = [];
6
for(var i = 0 ; i < array.length ; i++)
7
{
8
if(i != index)
9
{
10
newArray.push(array[i]);
11
}
12
}
13
array = newArray; // where it saves the variable
14
}
15
16
removeItem(list,0);
17
Advertisement
Answer
You can create a prototype function, see this
JavaScript
1
6
1
Array.prototype.removeItem = function(what) {
2
if (this.indexOf(what) >= 0) this.splice(this.indexOf(what), 1);
3
}
4
var foo = [1, 2, 3];
5
foo.removeItem(2);
6
console.log(foo);