假设我有以下内容:

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)

当前回答

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

_.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)})

其他回答

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

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

如果你想从一个已知唯一对象属性的数组中过滤掉重复值,你可以使用下面的代码片段:

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

let uniqueValues = [...arr.reduce((map, val) => {
    if (!map.has(val.name)) {
        map.set(val.name, val);
    }
    return map;
}, new Map()).values()]

@Travis J字典答案在Typescript类型安全函数的方法

const uniqueBy = <T, K extends keyof any>(
  list: T[] = [],
  getKey: (item: T) => K,
) => {
  return list.reduce((previous, currentItem) => {
    const keyValue = getKey(currentItem)
    const { uniqueMap, result } = previous
    const alreadyHas = uniqueMap[keyValue]
    if (alreadyHas) return previous
    return {
      result: [...result, currentItem],
      uniqueMap: { ...uniqueMap, [keyValue]: true }
    }
  }, { uniqueMap: {} as Record<K, any>, result: [] as T[] }).result
}

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

console.log(uniqueBy(array, el => el.age))

// [
//     {
//         "name": "Joe",
//         "age": 17
//     },
//     {
//         "name": "Carl",
//         "age": 35
//     }
// ]

我选取了随机样本,并将其与10万个项目进行了测试,如下所示:

let array=[]
for (var i=1;i<100000;i++){

 let j= Math.floor(Math.random() * i) + 1
  array.push({"name":"Joe"+j, "age":j})
}

这里是每一个的性能结果:

  Vlad Bezden Time:         === > 15ms
  Travis J Time: 25ms       === > 25ms 
  Niet the Dark Absol Time: === > 30ms
  Arun Saini Time:          === > 31ms
  Mrchief Time:             === > 54ms
  Ivan Nosov Time:          === > 14374ms

另外,我想提的是,由于项目是随机生成的,第二名是在Travis和Niet之间迭代。

我自己用TypeScript写了一个通用的例子,比如Kotlin's Array。distinctBy{}…

function distinctBy<T, U extends string | number>(array: T[], mapFn: (el: T) => U) {
  const uniqueKeys = new Set(array.map(mapFn));
  return array.filter((el) => uniqueKeys.has(mapFn(el)));
}

当然U是可哈希的。对于Objects,您可能需要https://www.npmjs.com/package/es6-json-stable-stringify