neem88
neem88

Reputation: 53

how to delete an entire element from an associative array in javascript

I am not too good in javascript.I have an associative array in which I am putting some values.Now to iterate through the array I am using a foreach loop.Inside the foreach loop, if a condition is met I want to delete the entire element and want no empty space in the array for efficiency.However I have no idea how to get the index of an array from a foreach loop.

here is my code:
for(var j = 0 ; j < i; j++){
        obstacles.push({ width:35, height:35, x:initialX, y:initialY});
    }

 //to iterate through the array
  obstacles.forEach(o => {
          o.x -= 2;
          context.fillRect(o.x, o.y, o.width, o.height); //create a rectangle with the elements inside the associative array
          //I need to get the index and delete the entire element and afterwards the array should resize with the other elements' index updated

        }

Upvotes: 0

Views: 137

Answers (1)

KooiInc
KooiInc

Reputation: 122936

To remove elements that comply to a certain condition from an array, Array.filter comes in handy. See MDN

let arr1 = [1,2,3,4,5,6,7,8,9,10];
// [...] to stuff to arr1
arr1 = arr1.filter(val => val % 2 === 0);
console.log(arr1);

Upvotes: 1

Related Questions