I have an JSON file with data inside of an user
[
{
"_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"
}
]
I had to sort every user by : if user has more than two names if user ids are consecutive and if user ids are numbers
I managed to sort user by more than two names and if ids are consecutive
userData.filter(({nameList}) =>
nameList.length > 2 &&
!nameList.some(({id}, index, array) => index && array[index - 1].id !== id - 1)
);
In the case that an object has an id as number I should not return the objects. How can I implement that in my code?
The output is expected to be all the arrays that meet the filter, and some() criteria. Which is if objects has more than 2 names, its ids are consecutive and the ids should be a number.
If you want to check if the id is of type number:
(typeof id == "number")
To check if can be cast to a number
(id == parseInt(id, 10))
The complete code then (you were close):
var userData = get_data();
userData = userData.filter(function(item) {
return item.nameList.length > 2 &&
item.nameList.every(function(item, index, arr) {
return parseInt(item.id) == item.id && (index == 0 || item.id - arr[index - 1].id == 1)
})
})
console.log(userData);
function get_data() {
return [{
"_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"
}
]
}
];
}
.as-console-wrapper {
max-height: 100% !important
}