Remove array element inside for loop – Javascript

In this article, you will learn, how to remove an array element in a for loop using Javascript. We will be looping in reverse.

Video tutorial:

You can use the following code:

// sample array
const categories = [
  {
    category: "Laptop",
    products: ["Macbook pro", "Acer aspire 5", "Dell XPS", "Lenovo Ideapad"]
  },
  
  {
    category: "Mobile",
    products: ["Samsung Galaxy S23", "Apple iPhone 15"]
  }
]

// looping through all array elements in reverse
for (let a = categories.length - 1; a >= 0; a--) {
  // condition criteria
  if (categories[a].products.length > 3) {
    // remove array element
    categories.splice(a, 1)
  }
}

This will delete all categories having more than 3 products.