I'm interested in utilizing Javascript's array.filter method to remove specific items from an array because of its elegant and readable syntax. However, I've noticed that instead of modifying the original array, filter simply returns a new array with the desired elements removed. This has led me to question why my implementation isn't yielding the expected results.
$scope.clearList = function () {
this.list = this.list.filter(function (item) {
return item.checked == true;
});
//...
}
My assumption was that by returning the newly filtered array, the variable this.list would now store only the filtered data. Unfortunately, that does not seem to be the case. Even though the code correctly filters the array when saved in an intermediate variable, this.list continues to hold all the original items.
Currently, I have resorted to a less elegant workaround where I loop through the filtered array and manually remove unwanted items from the original list. Could it be that my approach is flawed?
As a side note, I am working with Angular.js. While I'm unsure if this detail is relevant, the list being modified is generated from the following structure:
<div class="list" ng-repeat="list in lists">
<!-- ... -->
<ul>
<li ng-repeat="item in list">
<div>
<label>
<input type="checkbox" ng-model="item.checked"/>
{{item.name}}
</label>
<!-- ... -->
</div>
</li>
</ul>
<button class="btn clear-selected" ng-click="clearList()">
Remove Selected
</button>
</div>
To gain more insights into the issue, I have included some debugging information below:
var temp = this.list.filter(function (item) {
return item.checked == true;
});
this.list = temp;
Prior to execution, this.List contains 5 items while temp is undefined. After the first line runs, this.List retains 5 items and temp holds 2. Post the final line execution, this.List also contains 2 items but temp still has 2 items. Yet, despite these changes, it appears that the user interface bound to this.list fails to update properly, indicating that there might be an unrelated issue causing this unexpected behavior.