1

For my project, I have a list of students and am meant to use super basic regular expressions to check their grades. The A and B students are to be added to separate arrays for only those students. The code for doing so is as follows:

const aTest = new RegExp(/(A)/i);
const bTest =  new RegExp(/(B)/i);
const aStudents = [];
const bStudents = [];
for (var i = 0; i < students.length; i++) {
  if (aTest.test(students[i].grade)) {
    aStudents.push(students[i]);
  }
  if (bTest.test(students[i].grade)) {
    bStudents.push(students[i]);
  }
}

However, if I were to use forEach instead of a for loop, how should I go about doing so?

2 Answers 2

2

You just need to change every students[i] to the first parameter provided to the forEach (which references the current item being iterated over in the array), probably call it student:

students.forEach(student => {
  if (aTest.test(student.grade)) {
    aStudents.push(student);
  } else if (bTest.test(student.grade)) {
    bStudents.push(student);
  }
});

But if you have a regular expression literal already, there's no need for new RegExp - just assign the regular expression literal to the variable. Also, there's no need for a captured group if you just need to test:

const aTest = /A/i;
const bTest = /B/i;

Or, you might avoid regular expressions entirely and use (ES6) .includes instead:

  if (student.grade.includes('A')) {
    aStudents.push(student);
  } else if (student.grade.includes('B')) {
    bStudents.push(student);
  }
Sign up to request clarification or add additional context in comments.

Comments

1

I would use filter instead of forEach, yes it loops over the array twice but the code is clearer to read and understand

const aStudents = students.filter(student => student.grade.match(/A/i));
const bStudents = students.filter(student => student.grade.match(/B/i));

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.