Spot the bug - #122: Leaderboard Table

Why is my inventory ranker mutating the original list?

const potions = [{ name: "Elixir", power: 45 }, { name: "Brew", power: 90 }];

function getTopPotion(list) {
  const sorted = list.sort((a, b) => b.power - a.power);
  return sorted[0];
}

const best = getTopPotion(potions);
console.log(potions[0].name === "Elixir");

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

The sort method changes the array it is called on. It does not return a new array.

You can make a copy of list first. Something like [...list].sort(...) would work to keep the original potions array untouched.

Spot the Bug answer: The Array.prototype.sort() method sorts the elements of an array in place and returns the reference to the same array, thus mutating the original list.

The fix:

const sorted = [...list].sort((a, b) => b.power - a.power);

Why:
When list.sort() is called, it directly modifies the potions array because list is a reference to potions. To prevent this, a shallow copy of the array should be made before sorting. Using the spread operator [...list] creates a new array instance, allowing the sort operation to occur on the copy without affecting the original potions array.

First-answer leaderboard

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