0

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

        }
4
  • 1
    You mean this array index: obstacles.forEach((o, index) => ...) Commented Apr 5, 2020 at 16:27
  • @palaѕн i have tried and it worked..thank you loads Commented Apr 5, 2020 at 16:39
  • but how do I remove the element such that the array is resized and there are no empty space, also can a remove the element while in the foreach loop? Commented Apr 5, 2020 at 16:42
  • I dont think you can. u need to use .filter like @Kooilnc said or create a new array outside the loop and inside loop push items into it that meet the criteria Commented Apr 5, 2020 at 16:48

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.