1

I’m creating demonstration code for a presentation.

var fruitList = ["apple", "banana", "cherry", "durian", "elderberry", "fig", "grape", "huckleberry", "incaberry", "juniper", "kapok", "lime", "mango", "nectarine", "olive", "plum", "quince", "rambutan", "strawberry", "tangerine", "ugli", "vanilla", "watermelon", "xigua", "yarrow", "zhe"];
for (var i = 0; i < fruitList.length; i++) {
  if (fruitList[i].charAt(fruitList[i].length-1) == "y") {
    fruitList.splice(i, 1);
  }
}
console.log(fruitList);

This code is working almost perfectly, but there’s one strange problem: the incaberry. No matter how many times I rename it, or put another element before or after it, it never gets removed from the list.

I tried to introduce new elements to the list, hoping to discover it was some strange problem with indexing, but it still stayed in the list.

Through experimentation, I learned that for any set of consecutive elements ending in y, only the first will be removed. How do I fix this?

  • 1
    Consider a simpler case: `["ay", "by", "cy"]`. When i==0 , remove `ay`, then the list becomes like `["by", "cy"]`. Then i is changed to 1. So `by` is now at index 0, so your loop won't go to its index. Unless, for example, you change the i back to 0 again. Like, `i--` every time you splice it. – qrsngky Nov 14 '22 at 08:05

3 Answers3

1

use a filter method. with your condition written inside it Filter

    fruitList = fruitList.filter(item => item.charAt(item.length-1) != "y")

console.log(fruitList);
HexaCrop
  • 3,863
  • 2
  • 23
  • 50
1

That's because the huckleberry gets removed first, the incaberry takes its place, i gets increased and the check for the incaberry gets skipped. To prevent this, decrease i by one after fruitList.splice.

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
1

Please try this, you must reduce i when you match your condition and do the splicing.

var fruitList = ["apple", "banana", "cherry", "durian", "elderberry", "fig", "grape", "huckleberry", "incaberry", "juniper", "kapok", "lime", "mango", "nectarine", "olive", "plum", "quince", "rambutan", "strawberry", "tangerine", "ugli", "vanilla", "watermelon", "xigua", "yarrow", "zhe"];
for (var i = 0; i < fruitList.length; i++) {
  if (fruitList[i].at(-1) === "y") {
    fruitList.splice(i, 1);
    i--;
  }
}
console.log(fruitList);
programandoconro
  • 2,378
  • 2
  • 18
  • 33