You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合filter()与startsWith()方法过滤JavaScript数组

使用filter()结合startsWith()过滤people数组

嘿,这问题挺实用的,咱们一步步拆解怎么实现!先快速回顾下两个核心方法的作用:

  • filter():数组的遍历筛选方法,会把回调函数返回true的元素收集起来,返回一个新数组。
  • startsWith():字符串方法,用来判断当前字符串是否以指定前缀开头,返回布尔值,语法是str.startsWith(前缀[, 起始位置])。

针对你给出的people数组,我整理了几个常见的过滤场景示例,直接就能用:

示例1:过滤姓氏以'D'开头的人员

如果想找出所有姓氏(last字段)以字母'D'开头的人,代码可以这么写:

const people = [ { first: 'John', last: 'Doe', year: 1991, month: 6 }, { first: 'Jane', last: 'Doe', year: 1990, month: 9 }, { first: 'Jahn', last: 'Deo', year: 1986, month: 1 }, { first: 'Jone', last: 'Deo', year: 1992, month: 11 }, { first: 'Jhan', last: 'Doe', year: 1989, month: 4 }, { first: 'Jeon', last: 'Doe', year: 1992, month: 2 }, { first: 'Janh', last: 'Edo', year: 1984, month: 7 }, { first: 'Jean', last: 'Edo', year: 1981, month: 8}, ];

const filteredByLastStartD = people.filter(person => person.last.startsWith('D'));
console.log(filteredByLastStartD);

这段代码里,filter遍历每个person对象,检查person.last是否以'D'开头,符合条件的元素会被自动加入结果数组。

示例2:过滤名字以'Ja'开头的人员

要是想筛选名字(first字段)以'Ja'开头的人,只需要把判断条件换成person.first.startsWith('Ja'):

const filteredByFirstStartJa = people.filter(person => person.first.startsWith('Ja'));
console.log(filteredByFirstStartJa);

运行后会返回John、Jane、Jahn这几个对象,因为他们的名字都是以'Ja'开头的。

示例3:多条件组合过滤

还可以叠加多个筛选条件,比如找出名字以'J'开头,同时姓氏以'E'开头的人:

const filteredMultiCondition = people.filter(person => 
  person.first.startsWith('J') && person.last.startsWith('E')
);
console.log(filteredMultiCondition);

这里会返回Janh和Jean两个对象,完美匹配双重条件。

小提示:处理大小写敏感问题

startsWith()默认是大小写敏感的,如果需要忽略大小写判断,可以先把字符串转成小写(或大写)再做匹配:

// 过滤姓氏以'd'开头(不区分大小写)的人
const filteredCaseInsensitive = people.filter(person => 
  person.last.toLowerCase().startsWith('d')
);

这样就能灵活组合两个方法,完成各种个性化的数组过滤需求啦!

内容的提问来源于stack exchange,提问作者AndrewL64

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:31:02