Home > Software engineering >  Have problem with JavaScript .filter and .find to return items with specific letters
Have problem with JavaScript .filter and .find to return items with specific letters

Time:10-17

In the following JavaScript code, I am trying to get names that has letter "Y" or "y". When I looked up how to do that, I saw .filter and .find method. But this code only returns containsY = ['Tommy']. I tried for loop, but .find only returns the the value of the first element in the provided condition, and it doesn't return all names with "y"s. Is there any better way to get all of "Y" and "y" names?

const students = ["Tommy","Noah","Xander","Adil","Bradley","Nicholas","Damien"]

      let containsY = students.filter((student) => student.includes("Y"))

      //Look for name with "y", and push it to containsY
      containsY.push(students.find((student) => student.includes("y")))

      console.log(containsY)

CodePudding user response:

Your filter approach is fine. It's giving incorrect results because includes is case sensitive.

Instead, inside the filter callback, convert student to lowercase, then check whether it includes "y":

const students = ["Tommy","Noah","Xander","Adil","Bradley","Nicholas","Damien"]

const res = students.filter((student) => student.toLowerCase().includes("y"))

console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Either use a regular expression (which has the benefit of only requiring a single test)

const students = ["Tommy", "Noah", "Xander", "Adil", "Bradley", "Nicholas", "Damien"]
const result = students.filter(student => /y/i.test(student))
console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Or test for both .includes('y') and .includes('Y') in (a single) callback.

const students = ["Tommy", "Noah", "Xander", "Adil", "Bradley", "Nicholas", "Damien"]
const result = students.filter(student => student.includes('y') || student.includes('Y'));
console.log(result)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related