[Solved] How to distinct json array by email using JAVASCRIPT [closed]


You can use the function reduce.

This alternative stores the previous emails to increment the count.

var array = [{    "_id": "5aaa4f8cd0ccf521304dc6bd",    "email": "[email protected]"  },  {    "_id": "5aaa50a0ac40d32404c8bab7",    "email": "[email protected]",  },  {    "_id": "5aa8ace3323eeb001414a2c5",    "email": "[email protected]"  },  {    "_id": "5aa86645323eeb001414a2af",    "email": "[email protected]"  },  {    "_id": "5aa92c7d66c8820014813ed8",    "email": "[email protected]"  }];

var count = array.reduce((a, c) => {
  if (!a[c.email]) a[c.email] = ++a.count;
  return a;
}, {count: 0}).count;

console.log(count);

Using the object Set

  • Map to arrays of emails.
  • Initialize the object Set with that mapped array.
  • Get the count using the property size.
var array = [{    "_id": "5aaa4f8cd0ccf521304dc6bd",    "email": "[email protected]"  },  {    "_id": "5aaa50a0ac40d32404c8bab7",    "email": "[email protected]",  },  {    "_id": "5aa8ace3323eeb001414a2c5",    "email": "[email protected]"  },  {    "_id": "5aa86645323eeb001414a2af",    "email": "[email protected]"  },  {    "_id": "5aa92c7d66c8820014813ed8",    "email": "[email protected]"  }],
    mapped = array.map(e => e.email),
    set = new Set(mapped),
    count = set.size;

console.log(count);

solved How to distinct json array by email using JAVASCRIPT [closed]