Home > Blockchain >  .match() matches only some of an identical array of strings
.match() matches only some of an identical array of strings

Time:07-16

I'm matching an array of strings against a regex:

for (let subject_index in subjects) {
      if (subjects[subject_index].match(/.*Overview of Investor.*/i)) {
        subjects.splice(subject_index, 1)
      }
    }

The array subjects contains nine identical strings, all of them Overview of Investor. When I run this loop, it correctly matches five of the strings and does not match on the other four, even though all the strings are identical. Am I missing something?

CodePudding user response:

You're editing the array while iterating over it, which can cause weird problems. You can do this in a better way with Array.filter.

subjects = subjects.filter(subject => !subject.match(/.*Overview of Investor.*/i));

This way, you are not editing the array while reading the elements.

Edit: As noted in the comments, this solution removes the matched strings, because that is what the original poster's solution is trying to do. If you want to keep the matched strings, use

subjects = subjects.filter(subject => subject.match(/.*Overview of Investor.*/i));

This is the same code but without the exclamation point.

CodePudding user response:

Do not mutate your array within your loop. Create a new array to add your matches to.

let subjects = ["Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor", "Overview of Investor"];
let ans = [];

for (let subject_index in subjects) {
      if (subjects[subject_index].match(/.*Overview of Investor.*/i)) {
        ans.push(subjects[subject_index]);
      }
 }

  • Related