假设我有以下内容:

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)

当前回答

我知道这是一个老问题,相对来说回答得很好,我给出的答案将得到完整的对象(我在这篇文章的许多评论中看到了建议)。它可能“俗气”,但就可读性而言,它似乎比许多其他解决方案干净得多(尽管效率较低)。

这将返回数组中完整对象的唯一数组。

let productIds = data.map(d => { 
   return JSON.stringify({ 
      id    : d.sku.product.productId,
      name  : d.sku.product.name,
      price : `${d.sku.product.price.currency} ${(d.sku.product.price.gross / d.sku.product.price.divisor).toFixed(2)}`
   })
})
productIds = [ ...new Set(productIds)].map(d => JSON.parse(d))```

其他回答

如果你像我一样喜欢更“功能性”而不影响速度,这个例子使用封装在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]
    }
}, [{},[]])

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

这是ES6版本的一个轻微变化,如果你需要整个对象:

let arr = [
    {"name":"Joe", "age":17}, 
    {"name":"Bob", "age":17}, 
    {"name":"Carl", "age": 35}
]
arr.filter((a, i) => arr.findIndex((s) => a.age === s.age) === i) // [{"name":"Joe", "age":17}, {"name":"Carl", "age": 35}]

如果你想迭代唯一的项目,使用这个: (更灵活的https://stackoverflow.com/a/58429784/12496886版本)

Const数组= [ {" name ":“乔”,“年龄”:17}, {" name ":“鲍勃”、“年龄”:17}, {"name":"Carl", "age": 35}, ]; const uniqBy = (arr, selector = (item) => item) => { const map = new map (); arr.forEach((item) => { Const道具=选择器(item); If (!map.has(prop))映射。集(道具、物品); }); 返回[…map.values ()); } const uniqItems = uniqBy(array, (item) => item.age); console.log('uniqItems: ', uniqItems);

如果你只需要唯一的值,使用这个: (为完整起见,https://stackoverflow.com/a/35092559/12496886副本)

Const数组= [ {" name ":“乔”,“年龄”:17}, {" name ":“鲍勃”、“年龄”:17}, {"name":"Carl", "age": 35}, ]; Const uniq = (items) =>[…]新组(项目)]; const uniqAges = uniq(array.map((item) => item.age)); console.log('uniqAges: ', uniqAges);

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

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

我自己用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