I’ve been trying to work out a problem I’m having. I have an array with objects in it, like this:
JavaScript
x
33
33
1
var array = [
2
{
3
name: "Steven Smith",
4
Country: "England",
5
Age: 35
6
},
7
{
8
name: "Hannah Reed",
9
Country: "Scottland",
10
Age: 23
11
},
12
{
13
name: "Steven Smith",
14
Country: "England",
15
Age: 35
16
},
17
{
18
name: "Robert Landley",
19
Country: "England",
20
Age: 84
21
},
22
{
23
name: "Steven Smith",
24
Country: "England",
25
Age: 35
26
},
27
{
28
name: "Robert Landley",
29
Country: "England",
30
Age: 84
31
}
32
];
33
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:
JavaScript
1
28
28
1
[
2
{
3
name: "Steven Smith",
4
Country: "England",
5
Age: 35
6
},
7
{
8
name: "Steven Smith",
9
Country: "England",
10
Age: 35
11
},
12
{
13
name: "Robert Landley",
14
Country: "England",
15
Age: 84
16
},
17
{
18
name: "Steven Smith",
19
Country: "England",
20
Age: 35
21
},
22
{
23
name: "Robert Landley",
24
Country: "England",
25
Age: 84
26
}
27
];
28
If been trying to do
JavaScript
1
6
1
array.forEach(function(name, age){
2
if(array.name == name || array.age == age){
3
console.log(the result)
4
}
5
})
6
But that only checks if the values of the object is equal to them self.
Can anybody help me?
Advertisement
Answer
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.
JavaScript
1
10
10
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}]
2
3
var result = Object.values(array.reduce((c, v) => {
4
let k = v.name + '-' + v.Age;
5
c[k] = c[k] || [];
6
c[k].push(v);
7
return c;
8
}, {})).reduce((c, v) => v.length > 1 ? c.concat(v) : c, []);
9
10
console.log(result);