使用Javascript查找对象中的重复值 [英] Find duplicate values in objects with Javascript

查看:110
本文介绍了使用Javascript查找对象中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力解决自己遇到的问题.我有一个包含对象的数组,像这样:

I've been trying to work out a problem I'm having. I have an array with objects in it, like this:

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
  }
];

我想获取其中具有重复值并基于要搜索的值的对象.即,我想获取具有重复值名称"和年龄"但重复国家/地区"的对象,所以我最终得到:

I want to get the objects that have duplicate values in them and based on what values to search for. I.e , I want to get the object that has a duplicate value "name" and "age" but nog "country" so I will end up with:

[
  {
    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)
}
})

但这仅检查对象的值是否等于它们自己.

But that only checks if the values of the object is equal to them self.

有人可以帮助我吗?

推荐答案

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

You can use 2 reduce. The first one is to group the array. The second one is to include only the group with more than 1 elements.

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查找对象中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆