Assuming I have the following:
(假设我有以下内容:)
var array =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
]
What is the best way to be able to get an array of all of the distinct ages such that I get an result array of:
(能够获得所有不同年龄的数组的最佳方法是什么,这样我得到以下结果数组:)
[17, 35]
Is there some way I could alternatively structure the data or better method such that I would not have to iterate through each array checking the value of "age" and check against another array for its existence, and add it if not?
(是否有某种方法可以替代性地构造数据或更好的方法,以使我不必遍历每个数组来检查“ age”的值并检查另一个数组是否存在,如果没有,则添加它?)
If there was some way I could just pull out the distinct ages without iterating...
(如果有某种方法,我可以不重复就退出不同的年龄...)
Current inefficent way I would like to improve... If it means that instead of "array" being an array of objects, but a "map" of objects with some unique key (ie "1,2,3") that would be okay too.
(我想改善当前无效的方法...如果这意味着不是“数组”是对象数组,而是带有一些唯一键(即“ 1,2,3”)的对象“映射”也可以)
Im just looking for the most performance efficient way.(我只是在寻找最高效的方式。)
The following is how I currently do it, but for me, iteration appears to just be crummy for efficiency even though it does work...
(以下是我目前的操作方式,但是对我来说,即使迭代确实有效,迭代似乎也很糟糕。)
var distinct = []
for (var i = 0; i < array.length; i++)
if (array[i].age not in distinct)
distinct.push(array[i].age)
ask by Rolando translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…