javascript - 使用 Javascript 在对象中查找重复值

标签 javascript arrays function sorting

我一直在努力解决我遇到的问题。我有一个包含对象的数组,如下所示:

var array = [
  {
    name: "Steven Smith",
    Country: "England",
    Age: 35
  },
  {
    name: "Hannah Reed",
    Country: "Scottland",
    Age: 23
  },
  {
    name: "Steven Smith",
    Country: "England",
    Age: 35
  },
  {
    name: "Robert Landley",
    Country: "England",
    Age: 84
  },
  {
    name: "Steven Smith",
    Country: "England",
    Age: 35
  },
  {
    name: "Robert Landley",
    Country: "England",
    Age: 84
  }
];

我想获取其中具有重复值的对象,并基于要搜索的值。即,我想获得具有重复值“name”和“age”但没有“country”的对象,所以我最终会得到:

[
  {
    name: "Steven Smith",
    Country: "England",
    Age: 35
  },
  {
    name: "Steven Smith",
    Country: "England",
    Age: 35
  },
  {
    name: "Robert Landley",
    Country: "England",
    Age: 84
  },
  {
    name: "Steven Smith",
    Country: "England",
    Age: 35
  },
  {
    name: "Robert Landley",
    Country: "England",
    Age: 84
  }
];

如果一直在努力做

array.forEach(function(name, age){
  if(array.name == name || array.age == age){
    console.log(the result)
}
})

但这只会检查对象的值是否等于它们自身。

谁能帮帮我?

最佳答案

您可以使用 2 个reduce。第一个是对数组进行分组。第二种是仅包括具有 1 个以上元素的组。

var array = [{"name":"Steven Smith","Country":"England","Age":35},{"name":"Hannah Reed","Country":"Scottland","Age":23},{"name":"Steven Smith","Country":"England","Age":35},{"name":"Robert Landley","Country":"England","Age":84},{"name":"Steven Smith","Country":"England","Age":35},{"name":"Robert Landley","Country":"England","Age":84}]

var result = Object.values(array.reduce((c, v) => {
  let k = v.name + '-' + v.Age;
  c[k] = c[k] || [];
  c[k].push(v);
  return c;
}, {})).reduce((c, v) => v.length > 1 ? c.concat(v) : c, []);

console.log(result);

关于javascript - 使用 Javascript 在对象中查找重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840157/

相关文章:

c++ - 使用 TBB 在 vector 中运行函数会给出不正确的输出

c++ - Hook 内部函数 : How do the the parameters look like?

javascript - typeof !== "undefined"与 != null

arrays - Delphi XE 字节数组索引

php - 从其中包含内爆函数的查询获取输出

c - 使用 malloc() 分配内存时出错,只能向表中添加一项

c函数指针解释

javascript - 添加网页 View 2次

c# - 在另一个CheckBox的基础上勾选取消勾选所有CheckBox

javascript - 拉斐尔翻译函数到变换函数