如何过滤JS对象数组:筛选nameList超2项且id连续的用户数据
JSON数据双规则过滤实现方案
需求说明
需要对存储用户信息的JSON数组做过滤,最终返回同时满足以下两个条件的条目:
- 用户对应的
nameList数组包含超过2个带有效name值的姓名条目 nameList数组内所有条目的id为连续数值
实现约束:禁止使用for循环,仅可使用map/filter/every/sort等ES6标准数组方法完成
参考数据结构
[ { "_id": "62bd5fba34a8f1c90303055c", "index": 0, "email": "mcdonaldholden@xerex.com", "nameList": [ { "id": 0, "name": "Wendi Mooney" }, { "id": 2, "name": "Holloway Whitehead" } ] }, { "_id": "62bd5fbac3e5a4fca5e85e81", "index": 1, "nameList": [ { "id": 0, "name": "Janine Barrett" }, { "id": 1, "name": "Odonnell Savage" }, { "id": 2, "name": "Patty Owen" } ] } ]
已实现的基础逻辑
目前已经完成nameList有效条目数大于2的筛选代码:
userData.filter((names,i) => { return names?.nameList?.filter(names => { return names.name;}).length > 2 ; })
完整可运行代码
id连续判断核心逻辑:先提取所有id值做升序排序(兼容原数组id乱序场景),再校验每一项id是否等于「序列最小值 + 当前索引」,全部符合则判定为连续序列。
const filteredResult = userData.filter(user => { // 校验有效姓名条目数量 const validNameList = user?.nameList?.filter(nameItem => nameItem.name) || []; if (validNameList.length <= 2) return false; // 提取id并排序,无需循环即可完成连续校验 const sortedIds = validNameList.map(item => item.id).sort((a, b) => a - b); const isIdConsecutive = sortedIds.every((id, idx) => id === sortedIds[0] + idx); return isIdConsecutive; });
优化提示:如果业务上能保证
nameList本身就是按id顺序存储的,可以省略排序步骤,直接提取id后做连续校验,运行性能更高。
内容的提问来源于stack exchange,提问作者Metgher Andrei
相关产品推荐
相关产品推荐

