假设我有以下内容:

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)

当前回答

清洁解决方案

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

其他回答

清洁解决方案

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

已经有许多有效的答案,但我想添加一个只使用reduce()方法的答案,因为它干净而简单。

function uniqueBy(arr, prop){
  return arr.reduce((a, d) => {
    if (!a.includes(d[prop])) { a.push(d[prop]); }
    return a;
  }, []);
}

像这样使用它:

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

var ages = uniqueBy(array, "age");
console.log(ages); // [17, 35]

我只需要映射和删除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循环将会更“有效”。

使用集合和过滤器。这维持了秩序:

Let unique = (items) => { const s = new Set(); 返回items.filter((item) => { If (s.has(item)) { 返回错误; } s.add(项); 返回true; }); } console.log ( 独特的( [ 1, 2, 2, 3, 3, 3 ] ) ); /* 输出: [ “一”, “两个”, “三” ] * /

使用新的Ecma功能很棒,但并不是所有用户都有这些功能。

下面的代码将附加一个名为distinct的新函数到Global Array对象。 如果您试图获取对象数组的不同值,则可以传递值的名称以获取该类型的不同值。

Array.prototype.distinct = function(item){   var results = [];
for (var i = 0, l = this.length; i < l; i++)
    if (!item){
        if (results.indexOf(this[i]) === -1)
            results.push(this[i]);
        } else {
        if (results.indexOf(this[i][item]) === -1)
            results.push(this[i][item]);
    }
return results;};

请查看我在CodePen中发布的演示。