Find duplicate values in objects with Javascript

前端 未结 5 772
[愿得一人]
[愿得一人] 2021-01-12 01:47

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         


        
5条回答
  •  渐次进展
    2021-01-12 02:44

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

提交回复
热议问题