I'm trying to make a function that can remove an element from inside a forEach loop.
The Function:
loopAndEdit = function(array,callback) {
var helper = {
data:{},
get:function() {
return helper.data;
},
remove:function() {
index = array.indexOf(helper.data);
array.splice(index,1);
return true;
}
};
tempArray = array;
tempArray.forEach(function(row) {
helper.data = row;
callback(helper)
});
}
To test it I loop through an array and try to remove all the elements:
names = ['abe','bob','chris'];
loopAndEdit(names,function(helper){
console.log('Working on ' + helper.data);
helper.remove();
});
console.log(names);
The output is:
Working on abe
Working on chris
[ 'bob' ]
I expect the output to look something like:
Working on abe
Working on bob
Working on chris
[]
I have a feeling it may be the helper.remove() causing trouble but I'm unsure at this point.
Thanks for the help!