简体   繁体   中英

How can I filter the array of objects by: if object ids are consective

I have a JSON file with data inside. I have to filter the data by : if user has more than two names, and if user ids are consecutive. The JSON file :

[
{
"_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"
  }
]
}, ...

I have managed to find an a solution to filter if the users have more than two names : userData.filter((names,i) => { return names?.nameList?.filter(names => { return names.name;}).length > 2 ; }) But I cant seem to grasp myself around the concept of filtering the consecutive ids. Also I was advised to not use any for loops at all. Only ES6 array loops like map, forEach and filter.

Here's a solution that uses every() to compare the ID of every element with the previous ID:

const result = data.filter(({nameList}) =>
  nameList.length > 2 &&
  nameList.every(({id}, i, a) => !i || id === a[i - 1].id + 1)
);

Complete snippet:

 const data = [{ "_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" }] }]; const result = data.filter(({nameList}) => nameList.length > 2 && nameList.every(({id}, i, a) => !i || id === a[i - 1].id + 1) ); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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