1

I am creating a program that involves removing text from an array. If a letter is included in a word in the array, then that word will be removed. My first test was successful, a simple regular expression with a small array:

var regex = /z/;
var words = ["eggs", "zebras", "lampshade"];

for (i = 0; i < words.length; i++) {
  let testResult = regex.test(words[i]);

  if (!testResult) {
    words.splice(i, 1);
  }
}
console.log(words);

As expected, it returned [ 'zebras' ]. Because this was successful, I quickly scaled up using an npm package called "an-array-of-english-words". I ran my new script:

const masterWords = require("an-array-of-english-words");
var regex = /z/;
var words = masterWords;

for (i = 0; i < words.length; i++) {
  let testResult = regex.test(words[i]);

  if (!testResult) {
    words.splice(i, 1);
  }
}
console.log(words);

Every time I run it it ends up returning values that do not abide by the regular expression. For example, the code above returned ['aa', 'aahed', 'aahs', ...] as its first few values. Do I have to change my code to deal with a bigger array? Am I making a stupid mistake I didn't notice?

2
  • Can you try using it like this ? console.log(words.filter(d => /z/.test(d))) Commented May 24, 2020 at 14:21
  • Great happy to hear that ! Commented May 24, 2020 at 14:33

2 Answers 2

1

I think it may be due to the fact that you are splicing the array and looping it at the same time.

For ex. if the length of array is 5 and the current index is 2, after splicing the array, the item at the index 3 will be moved to the index 2, and will be skipped in the next iteration, since the next index will be 3.

So, you can create a clone of the words and change it, while iterating the original array.

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

1 Comment

Yes, you can verify this by trying this array: ['a', 'a', 'z', 'a', 'a'] You'll see ['a', 'z', 'a'] It seems every false value will let through the next value, regardless if it's true or false.
0

@Joey , in official documentation if you see , try using it this way as a workaround . Also @Igor Moraru's answer explains why the issue might be happening.

console.log(words.filter(d => /z/.test(d))) 

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.