Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

arrays - Find duplicate values in objects with 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
  }
];

If been trying to do

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.

Can anybody help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...