[英]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:我有一个 JSON 文件,其中包含一个包含数据的对象数组:
[
{
"_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.我的工作是过滤具有两个以上名称且 id 连续的 arrays。 I managed to sort users with more than two
user.name
but cant grasp the concept of filtering consecutive id numbers我设法对具有两个以上
user.name
的用户进行排序,但无法掌握过滤连续 ID 号的概念
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
Which returns me the objects with more than two user names.这会返回具有两个以上用户名的对象。
filter
takes a function that returns true
if you want to retain the item or false
if not. filter
采用 function 如果要保留项目则返回true
,否则返回false
。 In this function, you could check the length of the nameList
, and then iterate over its members and make sure their id
s are consecutive:在这个 function 中,您可以检查
nameList
的长度,然后遍历其成员并确保它们的id
是连续的:
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;
});
a item should need tow conditions,one is nameList length is two,the other is the itemId of nameList is consecutive;一个item需要两个条件,一个是nameList的长度是两个,一个是nameList的itemId是连续的; 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希望这对你有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.