假设我有以下内容:

var array = 
    [
        {"name":"Joe", "age":17}, 
        {"name":"Bob", "age":17}, 
        {"name":"Carl", "age": 35}
    ]

获得所有不同年龄的数组的最佳方法是什么,这样我就得到了一个结果数组:

[17, 35]

是否有一些方法,我可以选择结构数据或更好的方法,这样我就不必遍历每个数组检查“年龄”的值,并检查另一个数组是否存在,如果没有添加它?

如果有某种方法可以让我不用迭代就能得到不同的年龄……

目前效率低下的方式,我想改进…如果它的意思不是“数组”是一个对象的数组,而是一个对象的“映射”与一些唯一的键(即。"1,2,3")也可以。我只是在寻找最高效的方式。

以下是我目前的做法,但对我来说,迭代似乎只是为了提高效率,即使它确实有效……

var distinct = []
for (var i = 0; i < array.length; i++)
   if (array[i].age not in distinct)
      distinct.push(array[i].age)

当前回答

如果你像我一样喜欢更“功能性”而不影响速度,这个例子使用封装在reduce闭包中的快速字典查找。

var array = 
[
    {"name":"Joe", "age":17}, 
    {"name":"Bob", "age":17}, 
    {"name":"Carl", "age": 35}
]
var uniqueAges = array.reduce((p,c,i,a) => {
    if(!p[0][c.age]) {
        p[1].push(p[0][c.age] = c.age);
    }
    if(i<a.length-1) {
        return p
    } else {
        return p[1]
    }
}, [{},[]])

根据这个测试,我的答案比提议的答案快两倍

其他回答

Const数组= [{ “名称”:“乔”, “年龄”:17 }, { “名称”:“鲍勃”, “年龄”:17 }, { “名称”:“卡尔”, “年龄”:35 } ] const uniqueArrayByProperty = (array, callback) => { 返回数组中。Reduce ((prev, item) => { Const v =回调(项目); If (! prew .includes(v)) 返回上一页 },[]) } console.log(uniqueArrayByProperty(array, it => .age));

underscore.js _.uniq (_.pluck(数组,“年龄”))

@travis-j的forEach版本的答案(对现代浏览器和Node JS世界很有帮助):

var unique = {};
var distinct = [];
array.forEach(function (x) {
  if (!unique[x.age]) {
    distinct.push(x.age);
    unique[x.age] = true;
  }
});

Chrome v29.0.1547更快34%:http://jsperf.com/filter-versus-dictionary/3

和一个通用的解决方案,需要一个mapper函数(略慢于直接映射,但这是预期的):

function uniqueBy(arr, fn) {
  var unique = {};
  var distinct = [];
  arr.forEach(function (x) {
    var key = fn(x);
    if (!unique[key]) {
      distinct.push(key);
      unique[key] = true;
    }
  });
  return distinct;
}

// usage
uniqueBy(array, function(x){return x.age;}); // outputs [17, 35]

原始类型

var unique = [...new Set(array.map(item => item.pritiveAttribute))];

对于复杂类型,例如对象

var unique = [...new DeepSet(array.map(item => item.Object))];

export class DeepSet extends Set {

  add (o: any) {
    for (let i of this)
      if (this.deepCompare(o, i))
        return this;
    super.add.call(this, o);
    return this;
  };

  private deepCompare(o: any, i: any) {
    return JSON.stringify(o) === JSON.stringify(i)
  }
}

对于那些想要返回所有属性由键唯一的对象

Const数组= [ {"name": "Joe", "age": 17}, {"name": "Bob", "age": 17}, {"name": "Carl", "age": 35} ] Const key = 'age'; const arrayUniqueByKey =[…]新地图(数组。地图(项= > (项目(关键),项目))). values ()]; console.log (arrayUniqueByKey); / *输出 [ {"name": "Bob", "age": 17}, {"name": "Carl", "age": 35} ] * / //注意:这将选择列表中最后一个重复的项。