Spot the bug - #112: Card Grid

My grocery list totals are off, snacks vanish somehow

const groceries = [
  { item: "Apples", price: 3 },
  { item: "Bread", price: 2 },
  { item: "Chips", price: 4 },
  { item: "Soda", price: 1 }
];

function removeCheapItems(list, limit) {
  for (let i = 0; i < list.length; i++) {
    if (list[i].price < limit) {
      list.splice(i, 1);
    }
  }
  return list;
}

const result = removeCheapItems(groceries, 3);
console.log(result.map(g => g.item));

Reply with what is broken and how you would fix it.

Splice isn’t the right method for this?

Fair question.

My short take is based on patterns people keep reporting in practice.

The issue is splice() while looping forward it shifts the next item into the current index, so the loop skips it. Use filter() instead:

function removeCheapItems(list, limit) {

return list.filter(g => g.price >= limit);

}

This removes the cheap items without mutating the original array.

Hmm, an interesting approach to the grocery list. We will reveal the solution later today.

@emmawalter5 - in the future, please use the code tag as part of the response to ensure the code snippets are formatted correctly :slight_smile:

1 Like

Spot the Bug answer: The loop does not correctly iterate over the list after an item is removed.

The fix:
Decrement the loop counter ‘i’ after splicing an item: ‘i–;’.

Why:
When an item is removed using ‘splice’, the array length decreases and subsequent elements shift their indices. If ‘i’ is not decremented, the next element in the original sequence is skipped because the loop counter advances past its new position.


Got it: @adnanahmed, @emmawalter5

First: @adnanahmed :trophy:

First-answer leaderboard

  1. @kirupa - 3 (firsts) :trophy:
  2. @adnanahmed - 1 (first)
  3. @emmawalter5 - 1 (first)

The backward iteration approach, while functionally correct for mutating arrays in place, introduces a slightly higher cognitive load for maintainability compared to filter(). I found a related kirupa.com article that can help you go deeper into this topic: Removing Elements From Array