Search code examples
javascriptarraysp5.js

My code is removing more than i want it to from my array


I am trying to make a coin collection system using p5.js and when i call the destroy function it deletes the object i want it to but also every object in the array after that.

destroy(){
    let index = coins.findIndex(function (item){
      return item == this;
    });
    
    coins.splice(index, 1);
  }

Solution

  • You can fix this by rewriting your findIndex to be

    destroy(){
        const index = coins.findIndex((item) => item === this);
        print(coins);
        coins.splice(index, 1);
        print(coins);
      }
    

    The triple equal sign is strict sameness check (see more at the mdn article), but was not the issue you were experiencing. I also refactored the function to a 1-line arrow function, which fixed the issue.

    "this" is undefined in the original function, which as @Robo Robok pointed out in his comment, means that the -1 is splicing off everything else in your list. Your second coin on the left, if you stand on it, "this" being undefined makes your findIndex function return -1, which splicing -1 removes the last coing from the array (the top-center coin). The draw function calls your collect method again, which does the same steps as before, but removing the last coin is now the second coin in the array (the one you're standing on), which is why the 1st coin (bottom center) is not removed.

    I'll admit I'm not certain why "this" was undefined, my best guess is it has something to do with how js objects are created. In the pre ECMA 2015 era, class objects were created in a way like this

    function MyObj(x, y){
        this.x = x;
        this.y = y;
    }
    
    const myObj = new MyObj(10, 50);
    

    Which leads me to believe that the callback function you supplied was using the scope of its own "this" as opposed to the coin "this"