简体   繁体   中英

Have problem with JavaScript .filter and .find to return items with specific letters

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)

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)

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM