0

I am detecting whether the mousepointer is within an ellipse that I have drawn in P5.js. When the mouse is in contact with the ellipse it should be deleted. I can achieve this by iterating over the array that stores the ellipses locations, checking if the mouse pointer is close enough to them to be warranted as inside by accessing the width element.w. This is a way to do it with a simple for loop:

for(var i = 0; i < locations.length; i++){
    var d = dist(mouseX, mouseY, locations[i].x, locations[i].y);
    if(d <= locations[i].w){
        locations.splice(i,1);
    }
}

I am wondering what the forEach loop way to do this would be. I premuse it would be something like the below code, but how do you actually destroy the element?

locations.forEach(function(element) {
    var d = dist(mouseX, mouseY, element.x, element.y);
    if(d <= element.w){
        //Destoy the element??? How do you do that????
    }                   
});
Oscar Chambers
  • 899
  • 9
  • 25
  • locations.forEach(function(element, i) { look you can an index to foreach https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/forEach and make a splice as demo behind – Álvaro Touzón Oct 16 '17 at 06:36
  • check the callback signature https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach function callback(currentValue, index, array) – JEY Oct 16 '17 at 06:36

3 Answers3

1

use filter function of Array, def variable preserve new array

Coco
  • 457
  • 1
  • 3
  • 14
1

Try this if you don't want to deal with browser compatibility issues for .remove()

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}

The snippet is from this answer https://stackoverflow.com/a/5933167/4724167.

Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36
0

Try using element.remove(), but this has cross-browser compatibility issues.

Nitheesh
  • 19,238
  • 3
  • 22
  • 49