假设我有以下内容:

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]

其他回答

Const数组= [ {" id ": " 93 ", "名称":" CVAM_NGP_KW "}, {" id ": " 94 ", "名称":" CVAM_NGP_PB "}, {" id ": " 93 ", "名称":" CVAM_NGP_KW "}, {" id ": " 94 ", "名称":" CVAM_NGP_PB "} ] 函数uniq(数组,字段){ 返回数组中。Reduce((累加器,电流)=> { 如果(! accumulator.includes(当前(领域))){ accumulator.push(当前(领域)) } 返回蓄电池; }, [] ) } Const id = uniq(数组,'id'); console.log (ids) / *输出 (“93”,“94”) * /

以防你需要整个对象的唯一性

const _ = require('lodash');

var objects = [
  { 'x': 1, 'y': 2 },
  { 'y': 1, 'x': 2 },
  { 'x': 2, 'y': 1 },
  { 'x': 1, 'y': 2 }
];

_.uniqWith(objects, _.isEqual);

[对象{x: 1, y: 2},对象{x: 2, y: 1}]

我对这个函数的看法是:

var result = [];
for (var len = array.length, i = 0; i < len; ++i) {
  var age = array[i].age;
  if (result.indexOf(age) > -1) continue;
  result.push(age);
}

你可以在这里看到结果(方法8) http://jsperf.com/distinct-values-from-array/3

目前正在使用typescript库以orm方式查询js对象。你可以从下面的链接下载。这个答案解释了如何使用下面的库来解决。

https://www.npmjs.com/package/@krishnadaspc/jsonquery?activeTab=readme

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

const ageArrayObj = new JSONQuery(ageArray)
console.log(ageArrayObj.distinct("age").get()) // outputs: [ { name: 'Bob', age: 17 }, { name: 'Carl', age: 35 } ]

console.log(ageArrayObj.distinct("age").fetchOnly("age")) // outputs: [ 17, 35 ]

Runkit live链接:https://runkit.com/pckrishnadas88/639b5b3f8ef36f0008b17512

Const数组= [ {"name": "Joe", "age": 17}, {"name": "Bob", "age": 17}, {"name": "Carl", "age": 35} ] Const key = 'age'; const arrayUniqueByKey =[…]新地图(数组。地图(项= > (项目(关键),项目))). values ()]; console.log (arrayUniqueByKey);