假设我有以下内容:

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)

当前回答

@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]

其他回答

回答这个老问题是毫无意义的,但是有一个简单的答案说明了Javascript的本质。Javascript中的对象本质上是哈希表。我们可以使用它来获得唯一键的哈希值:

var o = {}; array.map(function(v){ o[v.age] = 1; });

然后我们可以将哈希化简为一个唯一值的数组:

var a2 = []; for (k in o){ a2.push(k); }

这就是你所需要的。数组a2只包含唯一的年龄。

已经有许多有效的答案,但我想添加一个只使用reduce()方法的答案,因为它干净而简单。

function uniqueBy(arr, prop){
  return arr.reduce((a, d) => {
    if (!a.includes(d[prop])) { a.push(d[prop]); }
    return a;
  }, []);
}

像这样使用它:

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

var ages = uniqueBy(array, "age");
console.log(ages); // [17, 35]

如果这是PHP,我会建立一个数组的键和array_keys在最后,但JS没有这样的奢侈。相反,试试这个:

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);
}

如果你想迭代唯一的项目,使用这个: (更灵活的https://stackoverflow.com/a/58429784/12496886版本)

Const数组= [ {" name ":“乔”,“年龄”:17}, {" name ":“鲍勃”、“年龄”:17}, {"name":"Carl", "age": 35}, ]; const uniqBy = (arr, selector = (item) => item) => { const map = new map (); arr.forEach((item) => { Const道具=选择器(item); If (!map.has(prop))映射。集(道具、物品); }); 返回[…map.values ()); } const uniqItems = uniqBy(array, (item) => item.age); console.log('uniqItems: ', uniqItems);

如果你只需要唯一的值,使用这个: (为完整起见,https://stackoverflow.com/a/35092559/12496886副本)

Const数组= [ {" name ":“乔”,“年龄”:17}, {" name ":“鲍勃”、“年龄”:17}, {"name":"Carl", "age": 35}, ]; Const uniq = (items) =>[…]新组(项目)]; const uniqAges = uniq(array.map((item) => item.age)); console.log('uniqAges: ', uniqAges);

使用新的Ecma功能很棒,但并不是所有用户都有这些功能。

下面的代码将附加一个名为distinct的新函数到Global Array对象。 如果您试图获取对象数组的不同值,则可以传递值的名称以获取该类型的不同值。

Array.prototype.distinct = function(item){   var results = [];
for (var i = 0, l = this.length; i < l; i++)
    if (!item){
        if (results.indexOf(this[i]) === -1)
            results.push(this[i]);
        } else {
        if (results.indexOf(this[i][item]) === -1)
            results.push(this[i][item]);
    }
return results;};

请查看我在CodePen中发布的演示。