Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
How would I filter an array of objects by : If id numbers are consecutive

I have a JSON file that has an array of objects with data inside :

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

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 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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
});
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!