So I have something like this defined
var myList = [];
//I populate it like this
myList.push({ prop1: value1,
prop2: value2,
prop3: value3
});
Is it possible to remove items from the list, based on prop1 value w/o searching through the array?
4 Answers 4
No. You must loop over the array in some fashion, checking the properties of each object within, and perform removal as you hit them.
Comments
Here you go:
myList = myList.filter( function ( obj ) {
return obj.prop1 !== value;
});
where value is the value that you're testing against.
Live demo: http://jsfiddle.net/LBYfa/
So, if the value of the 'prop1' property is equal to the value that you're testing against, obj.prop1 !== value will evaluate to false and that element will be filtered out.
2 Comments
Array.prototype.filter is not available many widely deployed browsers. ( developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… ) Note that suggested shim code does as I said would be necessary--loops the array.filter method iterates over all array elements. That's generally how it works, it's not just the shim.Does this help:
Array.prototype.remove = function(s) {
var i = this.indexOf(s);
if(i != -1) this.splice(i, 1);
}
1 Comment
Is it required that myList have index of integral type? Might you instead use key => value pairs - that is, an associative array with the value of prop1 as the key? How likely is it that prop1 will be unique? If it's unlikely, consider implementing a multimap.