假设我有以下内容:

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)

当前回答

如果你有Array.prototype.includes或者愿意对它进行polyfill,这是可行的:

var ages = []; array.forEach(function(x) { if (!ages.includes(x.age)) ages.push(x.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]

下面的代码将显示唯一的年龄数组以及没有重复年龄的新数组

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

var unique = [];
var tempArr = [];
data.forEach((value, index) => {
    if (unique.indexOf(value.age) === -1) {
        unique.push(value.age);
    } else {
        tempArr.push(index);    
    }
});
tempArr.reverse();
tempArr.forEach(ele => {
    data.splice(ele, 1);
});
console.log('Unique Ages', unique);
console.log('Unique Array', data);```

从一组键中获取不同值的集合的方法。

您可以从这里获取给定的代码,并仅为所需的键添加映射,以获得唯一对象值的数组。

const listOfTags = [{ id: 1, label: "Hello", color: "red", sorting: 0 }, { id: 2, label: "World", color: "green", sorting: 1 }, { id: 3, label: "Hello", color: "blue", sorting: 4 }, { id: 4, label: "Sunshine", color: "yellow", sorting: 5 }, { id: 5, label: "Hello", color: "red", sorting: 6 }], keys = ['label', 'color'], filtered = listOfTags.filter( (s => o => (k => !s.has(k) && s.add(k)) (keys.map(k => o[k]).join('|')) )(new Set) ) result = filtered.map(o => Object.fromEntries(keys.map(k => [k, o[k]]))); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }

我只需要映射和删除dups:

var ages = array.map(function(obj) { return obj.age; });
ages = ages.filter(function(v,i) { return ages.indexOf(v) == i; });

console.log(ages); //=> [17, 35]

编辑:Aight !就性能而言,这不是最有效的方法,但在我看来,这是最简单、最易读的方法。如果你真的关心微观优化,或者你有大量的数据,那么一个常规的for循环将会更“有效”。

刚找到这个,我觉得很有用

_.map(_.indexBy(records, '_id'), function(obj){return obj})

还是用下划线,如果你有一个这样的对象

var records = [{_id:1,name:'one', _id:2,name:'two', _id:1,name:'one'}]

它只会给你唯一的对象。

这里发生的是indexBy返回一个像这样的映射

{ 1:{_id:1,name:'one'}, 2:{_id:2,name:'two'} }

因为它是一个映射,所有的键都是唯一的。

然后我把这个列表映射回数组。

如果你只需要不同的值

_.map(_.indexBy(records, '_id'), function(obj,key){return key})

请记住,键是作为字符串返回的,因此,如果您需要整数,您应该这样做

_.map(_.indexBy(records, '_id'), function(obj,key){return parseInt(key)})