如何从JavaScript对象的数组得到不同的值? [英] How to get distinct values from an array of objects in JavaScript?

查看:142
本文介绍了如何从JavaScript对象的数组得到不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下几点:

  VAR阵列=
    [
        {名:乔,时代:17},
        {名:鲍勃,时代:17},
        {名:卡尔,年龄:35}
    ]

什么是能够得到所有不同年龄段的数组的最佳方式,这样我得到的结果数组:

  [17,35]

有一些方法我也可以组织数据或更好的方法,这样我就不必通过每个阵列检查年龄的值进行迭代,并核对另一个数组为它的存在,如果不加呢?

如果有某种方式我可以拉出不同年龄不反复...

目前inefficent方式,我想提高...如果这意味着,而不是阵列是对象的数组,但一些独特的键(即1,2,3)对象的地图这将是好了。我只是在寻找性能最有效的方式。

以下是我目前是怎么做的,但对我来说,迭代似乎只是照出的,即使它的工作效率......

  VAR截然不同= []
对于(VAR I = 0; I< array.length,我++)
   如果(阵列[我]。年龄没有区别)
      distinct.push(数组[I]。年龄)


解决方案

如果这是PHP我会建立与键的数组,并采取 array_keys 末,但是JS就没有这样的奢侈。相反,试试这个:

  VAR标志= [],输出= [],L = array.length,我;
对于(i = 0; I<升;我++){
    如果(标志[阵列[我]。年龄])继续;
    标志[阵列[我]。年龄] = TRUE;
    output.push(数组[I]。年龄);
}

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?

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 (i.e. "1,2,3") that would be okay too. 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)

解决方案

If this were PHP I'd build an array with the keys and take array_keys at the end, but JS has no such luxury. Instead, try this:

var flags = [], output = [], l = array.length, i;
for( i=0; i<l; i++) {
    if( flags[array[i].age]) continue;
    flags[array[i].age] = true;
    output.push(array[i].age);
}

这篇关于如何从JavaScript对象的数组得到不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆