Not quite sure how to phrase this question (I am sure it has been asked before in some form).
My problem is essentially shown below (through some badly written pseudo-javascript code):
var list = []
for (i to somenumber)
list.push(new myObject);
list.foreach(function(item){
if (item.name === 'WhatIAmLookingFor')
item.delete() <--- This needs to remove the object from list
}
So as my amazing code alludes to I want to be able to remove the item from the list by calling a function on an object in the list.
Sorry if this is an ignorant question but I cant figure out how to do this.
1 Answer 1
Instead of deleting items, use filter to keep only "good" ones.
var list = [
{ name: 'foo' },
{ name: 'bar' },
{ name: 'removeMe' },
{ name: 'baz' }
];
list = list.filter(function(item) {
return item.name != 'removeMe'
});
document.write(JSON.stringify(list))
To remove an element "inside out", e.g. element.removeFrom(list), you need array.splice:
obj = function(name) {
this.name = name;
this.removeFrom = function(lst) {
for (var i = 0; i < lst.length; ) {
if (lst[i].name == this.name)
lst.splice(i, 1);
else
i++;
}
}
}
a = new obj('a');
b = new obj('b');
c = new obj('c');
x = new obj('remove');
list = [a, b, c, x, x, a, b, c, x]
x.removeFrom(list)
document.write(JSON.stringify(list))
answered Sep 18, 2014 at 15:23
georg
216k57 gold badges325 silver badges401 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Rabid
Can this be done from within the objects scope? I want to be calling one of the objects public methods to remove it from the list. But the array wont be within that functions scope.
georg
@Rabid: like
someObj.removeMe(someList)?Rabid
That was what I was thinking. But if I provide the array as a parameter to the function will it be passed by reference or value? Can you pass by reference in javascript?
georg
@Rabid: javascript is "pass by object value" - you pass a value, but this value is a pointer to an object. Therefore, you can use mutator methods, like
splice, on it - see the update.lang-js
indexOfanswers are useless here.forEach(uppercase E!)-function with georg 's filter-function, it should work. It's a clean solution you should try. You may come back and tell what went wrong.