假设我有以下内容:

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

其他回答

这就是你如何在2017年8月25日通过ES6使用新的Set来解决这个问题

打印稿

 Array.from(new Set(yourArray.map((item: any) => item.id)))

JS

 Array.from(new Set(yourArray.map((item) => item.id)))
[...new Set([
    { "name": "Joe", "age": 17 },
    { "name": "Bob", "age": 17 },
    { "name": "Carl", "age": 35 }
  ].map(({ age }) => age))]

让移动= [{id: 1、品牌:“B1”},{id: 2、品牌:“B2”},{id: 3、品牌:“B1”},{id: 4、品牌:“B1”},{id: 5、品牌:“B2”},{id: 6、品牌:“B3”}] let allBrandsArr = mobilePhones .map(row=>{ 返回row.brand; }); let uniqueBrands = allBrandsArr。filter((item, index, array) => (array . indexof (item) === index)); console.log('uniqueBrands ', uniqueBrands);

我认为你正在寻找groupBy函数(使用Lodash)

_personsList = [{"name":"Joe", "age":17}, 
                {"name":"Bob", "age":17}, 
                {"name":"Carl", "age": 35}];
_uniqAgeList = _.groupBy(_personsList,"age");
_uniqAges = Object.keys(_uniqAgeList);

产生的结果:

17,35

jsFiddle demo:http://jsfiddle.net/4J2SX/201/

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

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