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

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为数字类型的校验逻辑,最终返回满足全部三个筛选条件的用户数组。

实现方案

直接在现有判断条件中新增类型校验逻辑即可,注意两个细节:

  1. 要排除NaN的边界情况——typeof NaN的返回值也是number,但NaN不属于有效数字id
  2. 把类型校验放在连续判断逻辑之前,能避免非数字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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:06:23