JSFiddle - React, Tailwind, and code Playground
by r3wt
HTML
open the console to see the output.
JavaScript
function iteratingBigOFilter( arr, onKeep, onRemove ){
for(var i=0;i<arr.length;i++){
//some condition causing us to want to remove something from the array.
if( arr[i].value % 2 == 0 ){
onRemove(arr[i]);
arr.splice(i,1);//arrays are reference types. modifying it this way modifies the array as it was originally declared. no new allocation.
//this means array passed to function is also modified. we don't even have to return it.
--i;//decrement counter
continue; // next iteration of loop, at same index, which is now next item
}
//if we made it this far, it hasn't been removed
onKeep(arr[i]);
}
}
var arr = [{value: 1},{value: 2},{ value: 3}];
console.log(arr);
iteratingBigOFilter(arr,function onKeep(item){
console.log('kept item');
},
function onRemove(item){
console.log('removed item');
});
console.log(arr);//we have modified the array while iterating it in O(n) time. we can also do stuff with removed/kept items as needed