-4

How to distinct JSON array by value, using javascript. Below is my JSON array. I want to calculate the size of distinct elements.

 [
       {
                "_id": "5aaa4f8cd0ccf521304dc6bd",
                "email": "abc@gmail.com"
            },
            {
                "_id": "5aaa50a0ac40d32404c8bab7",
                "email": "pqr@gmail.com",
            },
            {
                "_id": "5aa8ace3323eeb001414a2c5",
                "email": "xyz@gmail.com"
            },
            {
                "_id": "5aa86645323eeb001414a2af",
                "email": "abc@gmail.com"

            }
    ]

The expected results should be 3.

  • 1
    Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Shai Katz Mar 15 '18 at 11:40
  • You can use something like this `Array.from(new Set(arr.map(({email}) => email)))` – Hassan Imam Mar 15 '18 at 11:44

2 Answers2

0

You can use the groupBy method of lodash https://lodash.com/docs/4.17.5#groupBy and then get the length of the result array

Fabio Carpinato
  • 1,121
  • 6
  • 13
0

You can use the function reduce.

This alternative stores the previous emails to increment the count.

var array = [{    "_id": "5aaa4f8cd0ccf521304dc6bd",    "email": "srjahir32@gmail.com"  },  {    "_id": "5aaa50a0ac40d32404c8bab7",    "email": "srjahir32@gmail.com",  },  {    "_id": "5aa8ace3323eeb001414a2c5",    "email": "g.anshul@gmail.com"  },  {    "_id": "5aa86645323eeb001414a2af",    "email": "bspilak@cooperequipment.ca"  },  {    "_id": "5aa92c7d66c8820014813ed8",    "email": "g.anshul@gmail.com"  }];

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": "srjahir32@gmail.com"  },  {    "_id": "5aaa50a0ac40d32404c8bab7",    "email": "srjahir32@gmail.com",  },  {    "_id": "5aa8ace3323eeb001414a2c5",    "email": "g.anshul@gmail.com"  },  {    "_id": "5aa86645323eeb001414a2af",    "email": "bspilak@cooperequipment.ca"  },  {    "_id": "5aa92c7d66c8820014813ed8",    "email": "g.anshul@gmail.com"  }],
    mapped = array.map(e => e.email),
    set = new Set(mapped),
    count = set.size;

console.log(count);
Ele
  • 33,468
  • 7
  • 37
  • 75