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

Time:07-06

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": "[email protected]",
"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.

CodePudding user response:

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": "[email protected]",
  "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);

  • Related