查找对象数组中的缺失值
我有一个 json 数组,其中有多个缺失的数字并且顺序不正确。查找丢失的数字的最佳方法是什么?
我的第一个想法是按顺序迭代并构造一个新的临时数组(因此,如果第一个键是 50,则它将转到 arr[50]),然后找出哪些没有键。不幸的是,这似乎效率极低。
更新: 这是我的 json 的一些内容:
"groups": [ { "group_id": "1", "group_name": "AABYODAADAAAW6KAAA", }, { "group_id": "5", "group_name": "AABYODAADAAAW6KAAB", }, { "group_id": "2", "group_name": "AABYODAADAAAW6KAAC", }, { "group_id": "3", "group_name": "AABYODAADAAAW6KAAAD", }, { "group_id": "6", "group_name": "AABYODAADAAAW6KAAAE", } ]
我正在对 group_id
进行排序,但数组长度超过 2,000。
I have a json array that has multiple missing numbers and is out of sequence. What is the best way to find which numbers are missing?
My First thought was to iterate through and construct a new temporary array in order (so if the first key is 50, it goes to arr[50]) and then find out which do not have a key. Unfortunately this seems extremely inefficient.
Update:
Here's a bit of my json:
"groups": [ { "group_id": "1", "group_name": "AABYODAADAAAW6KAAA", }, { "group_id": "5", "group_name": "AABYODAADAAAW6KAAB", }, { "group_id": "2", "group_name": "AABYODAADAAAW6KAAC", }, { "group_id": "3", "group_name": "AABYODAADAAAW6KAAAD", }, { "group_id": "6", "group_name": "AABYODAADAAAW6KAAAE", } ]
and I'm sorting group_id
, but the array length is over 2,000.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设这是您正在讨论的 JS 对象(而不是 JS 数组或 JSON 数组或 JSON 对象),您必须循环两次:
编辑:根据您更新的示例,您似乎有一个对象数组,其键是表示整数的字符串,并且您想找出可能丢失的键。这是可以做到这一点的代码:
Assuming this is a JS object you're talking about (and not a JS Array or a JSON Array or a JSON Object), you'll have to loop twice:
Edit: Based on your updated sample, it appears that you have an array of objects whose keys are strings that represent integers, and you want to figure out keys might be missing. Here's code that would do that:
也许您可以构造一个具有正确顺序的数字的单独数组,然后迭代第一个数组并让它从第二个数组中删除匹配的数组。新数组中剩下的应该是按顺序丢失的数字。
Perhaps you could construct a separate array with the numbers in the correct order, then iterate through the first array and have it remove ones from the secod array that match. What's leftin the newer array should be the missing numbers, in order.