简体   繁体   English

JavaScript .filter 和 .find 有问题以返回带有特定字母的项目

[英]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".在以下 JavaScript 代码中,我试图获取包含字母“Y”或“y”的名称。 When I looked up how to do that, I saw .filter and .find method.当我查找如何做到这一点时,我看到了.filter.find方法。 But this code only returns containsY = ['Tommy'] .但是这段代码只返回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.我试过for loop ,但.find只返回提供条件中第一个元素的值,它不会返回所有带有“y”的名称。 Is there any better way to get all of "Y" and "y" names?有没有更好的方法来获取所有“Y”和“y”名称?

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.你的filter方法很好。 It's giving incorrect results because includes is case sensitive.它给出了不正确的结果,因为includes区分大小写。

Instead, inside the filter callback, convert student to lowercase, then check whether it includes "y" :相反,在filter回调中,将student转换为小写,然后检查它是否包含"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.或者在(单个)回调中测试.includes('y').includes('Y')

 const students = ["Tommy", "Noah", "Xander", "Adil", "Bradley", "Nicholas", "Damien"] const result = students.filter(student => student.includes('y') || student.includes('Y')); console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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