JS对象数组过滤:实现数字类型连续id的多条件筛选
问题描述
我有一份存储用户数据的JSON文件,数据结构如下:
[ { "_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" } ] }, { "_id": "62bd5fbaf8f417d849c135db", "index": 2, "email": "pattyowen@xerex.com", "nameList": [ { "id": 0, "name": "Earline Goff" }, { "id": 1, "name": "Glenna Lawrence" }, { "id": 7, "name": "Bettye Sawyer" } ] } ]
需要筛选同时满足以下条件的用户对象:
- nameList数组长度大于2
- nameList内所有项的id为连续数值
- nameList内所有项的id均为数字类型
目前已经实现了前两个条件的过滤逻辑,代码如下:
userData.filter(({nameList}) => nameList.length > 2 && !nameList.some(({id}, index, array) => index && array[index - 1].id !== id - 1) );
需要在现有代码基础上补充id为数字类型的校验逻辑,最终返回满足全部三个筛选条件的用户数组。
实现方案
直接在现有判断条件中新增类型校验逻辑即可,注意两个细节:
- 要排除
NaN的边界情况——typeof NaN的返回值也是number,但NaN不属于有效数字id - 把类型校验放在连续判断逻辑之前,能避免非数字id参与数值运算时出现隐式类型转换,导致连续判断逻辑出错
修改后的完整代码如下:
userData.filter(({nameList}) => nameList.length > 2 && // 校验所有id为有效数字类型 nameList.every(({id}) => typeof id === 'number' && !Number.isNaN(id)) && !nameList.some(({id}, index, array) => index && array[index - 1].id !== id - 1) );
针对给出的样例数据,最终只会返回index为1的用户对象:它的nameList长度为3,id依次为0、1、2,全部是数字类型且数值连续,完全符合三个筛选条件;其余两个用户分别因为nameList长度不足、id不连续会被过滤。
内容的提问来源于stack exchange,提问作者Metgher Andrei
相关产品推荐
相关产品推荐

