2

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!

Subie
  • 373
  • 2
  • 16

1 Answers1

3

That is because your forEach loop is not able to loop through all 3 elements as you are removing one item inside the forEach loop.

So, say your forEach loop went through index 0 and than 1 where it removed index 1. At this point the length of array is changed to n-1 but the index inside the for loop is still the same.

In order to make a copy of an array so that it doesn't make changes in the original array.

Do this -

var tempArray = names.slice(0);

Instead of this -

var tempArray = names;
Cute_Ninja
  • 4,742
  • 4
  • 39
  • 63
  • tempArray = array; I make a copy of the array so I can loop through everything even if I remove an element. – Subie Oct 15 '14 at 16:19
  • @Subie: That isn't a copy. It's a reference to the original. –  Oct 15 '14 at 16:21
  • Ahhh, how does one make a copy then? Edit: looks like array.slice(0) does the trick. – Subie Oct 15 '14 at 16:22
  • Yes, but this is not a copy. Both tempArray and names are pointing to the same array. So, if you make any change in one of them, other will get changes as well – Cute_Ninja Oct 15 '14 at 16:22
  • @Subie: These are all questions that are frequently asked. To make a shallow copy, `tempArray = array.slice()` –  Oct 15 '14 at 16:24
  • Like this - > var tempArray = names.slice(0) – Cute_Ninja Oct 15 '14 at 16:25
  • array.slice() did the trick. Thanks for the help! – Subie Oct 15 '14 at 16:25
  • @Subie: Your approach though is much more involved and computationally expensive than needed. Is there a reason you chose this way to do it? –  Oct 15 '14 at 16:26