假设我有以下内容:

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)

当前回答

Const数组= [ {" id ": " 93 ", "名称":" CVAM_NGP_KW "}, {" id ": " 94 ", "名称":" CVAM_NGP_PB "}, {" id ": " 93 ", "名称":" CVAM_NGP_KW "}, {" id ": " 94 ", "名称":" CVAM_NGP_PB "} ] 函数uniq(数组,字段){ 返回数组中。Reduce((累加器,电流)=> { 如果(! accumulator.includes(当前(领域))){ accumulator.push(当前(领域)) } 返回蓄电池; }, [] ) } Const id = uniq(数组,'id'); console.log (ids) / *输出 (“93”,“94”) * /

其他回答

从一组键中获取不同值的集合的方法。

您可以从这里获取给定的代码,并仅为所需的键添加映射,以获得唯一对象值的数组。

const listOfTags = [{ id: 1, label: "Hello", color: "red", sorting: 0 }, { id: 2, label: "World", color: "green", sorting: 1 }, { id: 3, label: "Hello", color: "blue", sorting: 4 }, { id: 4, label: "Sunshine", color: "yellow", sorting: 5 }, { id: 5, label: "Hello", color: "red", sorting: 6 }], keys = ['label', 'color'], filtered = listOfTags.filter( (s => o => (k => !s.has(k) && s.add(k)) (keys.map(k => o[k]).join('|')) )(new Set) ) result = filtered.map(o => Object.fromEntries(keys.map(k => [k, o[k]]))); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }

Var数组= [ {" name ":“乔”,“年龄”:17}, {" name ":“鲍勃”、“年龄”:17}, {"name":"Carl", "age": 35} ]; Const ages =[…]新设置(数组。Reduce ((a, c) =>[…]A, c.age], []))]; console.log(年龄);

如果你使用的是ES6/ES2015或更高版本,你可以这样做:

const data = [
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' }, 
  { group: 'A', name: 'MM' },
  { group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']

这里有一个如何做的例子。

假设我们有这样的数据,arr=[{id:1,年龄:17},{id:2,年龄:19}…],那么我们就能找到像这样独特的物体

function getUniqueObjects(ObjectArray) {
    let uniqueIds = new Set();
    const list = [...new Set(ObjectArray.filter(obj => {
        if (!uniqueIds.has(obj.id)) {
            uniqueIds.add(obj.id);
            return obj;
        }
    }))];

    return list;
}

点击这里查看代码依赖链接

有LINQ .js - LINQ for JavaScript包(npm install LINQ), net开发人员应该很熟悉。

在样本中显示的其他方法中,有明显的过载。

通过属性值从对象数组中区分对象的示例 是

Enumerable.from(array).distinct(“$.id”).toArray();

从https://medium.com/@xmedeko i-recommend-you-to-try-https-github-com-mihaifm-linq-20a4e3c090e9