Reputation: 1820
I think it's too late at night for me to figure this out. Basically, I have a master array. I loop over it and remove an element if I find it. I do this for 4 elements.
In the end I want to display any leftover elements. The problem is that I'm not refreshing my array correctly after I remove an element.
Here's the code I'm using which I feel is too much brute force and not enough elegance.
var masks = ["valueOne","valueTwo","valueThree","valueFour","valueFive"];
$.each(masks,function(key,value){
if("valueOne" === value){
// do something
masks.splice($.inArray(value, masks),1);
}else if("valueTwo" === value){
// do something
masks.splice($.inArray(value, masks),1);
}else if("valueThree" === value){
masks.splice($.inArray(value, masks),1);
}else if("valueFour" === value){
// do something
masks.splice($.inArray(value, masks),1);
}
});
console.log( masks.toString() );
I'd expect the console to log "valueFive" but it doesn't. It logs this:
valueTwo,valueFour,valueFive
What's the correct way to refresh an array after updating it? Thanks for any helpful tips.
Upvotes: 2
Views: 1983
Reputation: 336
I think the proper way would be to use array.filter method of JavaScript. Filter expects a function and removes an element if this function returns false.
mask.filter(function(elem, index, array) {
if(elem==="value") return false;
return true;
}
Upvotes: 0
Reputation: 106
Here is the code dude...
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var masks = ["valueOne","valueTwo","valueThree","valueFour","valueFive"];
var count = 0;
$.each(masks,function(key,value){
//console.log( masks.toString() );
key = key - count;
//console.log(masks[key]);
if("valueOne" === masks[key]){
masks.splice($.inArray(masks[key], masks),1);
count++;
}
if("valueTwo" === masks[key]){
masks.splice($.inArray(masks[key], masks),1);
count++;
}
if("valueThree" === masks[key]){
masks.splice($.inArray(masks[key], masks),1);
count++;
}
if("valueFour" === masks[key]){
masks.splice($.inArray(masks[key], masks),1);
count++;
}
});
console.log( masks.toString() );
</script>
Upvotes: 1
Reputation: 123453
The issue is that $.each()
is iterating through the array by its indices.
(function(key,value){ ... })( 0, "valueOne" );
(function(key,value){ ... })( 1, "valueThree" );
(function(key,value){ ... })( 2, "valueFive" );
"valueTwo"
and "valueFour"
are skipped because .splice()
modifies the array, shifting them to an index that has already been visited by $.each()
.
masks[0] === "valueTwo"
masks[1] === "valueFour"
A quick solution to this is to provide a clone of the Array to iterate over, one that remains unaltered throughout, so you can safely modify the original.
$.each(masks.slice(0), function (key, value) {
// ...
});
Upvotes: 4