假设我有以下内容:

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)

当前回答

你可以使用lodash来写一段不那么冗长的代码

方法1:嵌套方法

    let array = 
        [
            {"name":"Joe", "age":17}, 
            {"name":"Bob", "age":17}, 
            {"name":"Carl", "age": 35}
        ]
    let result = _.uniq(_.map(array,item=>item.age))

方法二:方法链式或级联式

    let array = 
        [
            {"name":"Joe", "age":17}, 
            {"name":"Bob", "age":17}, 
            {"name":"Carl", "age": 35}
        ]
    let result = _.chain(array).map(item=>item.age).uniq().value()

您可以从https://lodash.com/docs/4.17.15#uniq阅读有关lodash的uniq()方法

其他回答

让移动= [{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);

如果你像我一样喜欢更“功能性”而不影响速度,这个例子使用封装在reduce闭包中的快速字典查找。

var array = 
[
    {"name":"Joe", "age":17}, 
    {"name":"Bob", "age":17}, 
    {"name":"Carl", "age": 35}
]
var uniqueAges = array.reduce((p,c,i,a) => {
    if(!p[0][c.age]) {
        p[1].push(p[0][c.age] = c.age);
    }
    if(i<a.length-1) {
        return p
    } else {
        return p[1]
    }
}, [{},[]])

根据这个测试,我的答案比提议的答案快两倍

如果你被ES5卡住了,或者由于某种原因不能使用new Set或new Map,并且你需要一个包含具有唯一键的值的数组(而不仅仅是唯一键的数组),你可以使用以下方法:

function distinctBy(key, array) {
    var keys = array.map(function (value) { return value[key]; });
    return array.filter(function (value, index) { return keys.indexOf(value[key]) === index; });
}

或者是TypeScript中的类型安全等效:

public distinctBy<T>(key: keyof T, array: T[]) {
    const keys = array.map(value => value[key]);
    return array.filter((value, index) => keys.indexOf(value[key]) === index);
}

用法:

var distinctPeople = distinctBy('age', people);

所有其他的答案:

返回唯一键的数组而不是对象(就像返回年龄列表而不是有唯一年龄的人); 使用ES6, new Set, new Map等可能无法提供给你; 没有可配置的键(比如将.age硬编码到不同的函数中); 假设键可以用于索引数组,但这并不总是正确的,TypeScript不允许这样做。

这个答案没有以上四个问题中的任何一个。

使用ES6

let array = [
  { "name": "Joe", "age": 17 },
  { "name": "Bob", "age": 17 },
  { "name": "Carl", "age": 35 }
];
array.map(item => item.age)
  .filter((value, index, self) => self.indexOf(value) === index)

> [17, 35]

清洁解决方案

export abstract class Serializable<T> {
  equalTo(t: Serializable<T>): boolean {
    return this.hashCode() === t.hashCode();
  }
  hashCode(): string {
    throw new Error('Not Implemented');
  }
}

export interface UserFields {
  firstName: string;
  lastName: string;
}

export class User extends Serializable<User> {
  constructor(private readonly fields: UserFields) {
    super();
  }
  override hashCode(): string {
    return `${this.fields.firstName},${this.fields.lastName}`;
  }
}

const list: User[] = [
  new User({ firstName: 'first', lastName: 'user' }),
  new User({ firstName: 'first', lastName: 'user' }),
  new User({ firstName: 'second', lastName: 'user' }),
  new User({ firstName: 'second', lastName: 'user' }),
  new User({ firstName: 'third', lastName: 'user' }),
  new User({ firstName: 'third', lastName: 'user' }),
];

/**
 * Let's create an map
 */
const userHashMap = new Map<string, User>();


/**
 * We are adding each user into the map using user's hashCode value
 */
list.forEach((user) => userHashMap.set(user.hashCode(), user));

/**
 * Then getting the list of users from the map,
 */
const uniqueUsers = [...userHashMap.values()];


/**
 * Let's print and see we did right?
 */
console.log(uniqueUsers.map((e) => e.hashCode()));