Home > Net >  How would I filter an array of objects by : If id numbers are consecutive
How would I filter an array of objects by : If id numbers are consecutive

Time:07-02

So I have an JSON file which has an array of objects with data inside :

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

My job is to filter the arrays that have more than two names and if their id are consecutive. I managed to sort users with more than two user.name but cant grasp around the concept of filtering consecutive id numbers

let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)

Which returns me the objects with more than two user names.

CodePudding user response:

filter takes a function that returns true if you want to retain the item or false if not. In this function, you could check the length of the nameList, and then iterate over its members and make sure their ids are consecutive:

retult = userData.filter(u => {
    if (u.nameList.length < 2) {
        return false;
    }
    for (let i = 1; i < u.nameList.length;   i) {
        if (u.nameList[i].id != u.nameList[i - 1].id   1) {
            return false;
        }
    }
    return true;
});

CodePudding user response:

a item should need tow conditions,one is nameList length is two ,the other is the itemId of nameList is consecutive; so first as you do :

`
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
`

; then `

let lister4 =  lister3.filter(names=>{
let idOfStr = names.nameList?.sort((a,b)=>a.id-b.id).map(item=>item.id).join("");
let resultStr = Array.from(idOfStr.length).fill( idOfStr[0]).map((item,index)=> item index).join('');
return idOfStr === resultStr
})

`

hope this is useful for you

  • Related