javascript - Mutated Array in AngularJS Filter -
i have custom angularjs filter containing few conditions. in else
condition splicing values out of array , returning array.
here's issue: splicing values out of array in else
condition mutates array, , if if
condition invoked afterwards, no longer processes original complete , pristine array, partial array containing remaining indexes after it's been spliced.
how can correct ensure i'm working on complete dataset each time filter run? tried working copy of array (using var newarr = items.splice(0)
)in else
block, whatever reason issue remains.
one option build new array in else
condition , return that, rather chipping away @ original array. since i'm dealing complex multi-nested data structure, simplicity's sake i'm looking solution can remove values.
angular.module("app", []). filter('department', function() { return function(items, args) { var filtered; var output = []; // return items when 'all departments' selected if (args.selecteddepartment.name == 'all departments' && args.selecteddepartment.id === undefined) { return items; } // return orders containing products selected department 'inclusive' option if (args.selecteddepartment.id !== undefined && !args.option) { (let = 0; < items.length; i++) { filtered = items[i].products.filter(function(item) { return item.order__r.department__r.id == args.selecteddepartment.id; }); if (filtered.length >= 1) { output.push(items[i]); } } // return products exact match selected department 'exclusive' option } else if (args.selecteddepartment.id !== undefined && args.option) { (let = 0; < items.length; i++) { (let j = 0; j < items[i].products.length; j++) { if (items[i].products[j].order__r.department__r.id != args.selecteddepartment.id) { items[i].products.splice(j, 1); } } if (items[i].products.length === 0) { items.splice(i, 1); } } return items; } return output; }; })
removing element given array mutating operation.
another approach implement non-mutating element removal. instead of directly modifying input array, remove function below return new array contains elements except specified one:
function remove(array, element) { return array.filter(e => e !== element); } const vowelsandx = ["a", "e", "i", "o", "u", "x"]; const vowels = remove(vowelsandx, "x"); vowels.tostring(); // "a,e,i,o,u"
Comments
Post a Comment