A guide to filtering a JSON array by email address with JavaScript

How can I identify distinct elements in a JSON array using JavaScript? Below is the example of my JSON array. I need to determine the size of unique elements.

 [
       {
                "_id": "5aaa4f8cd0ccf521304dc6bd",
                "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3e3d3c1f38323e3633713c3032">[email protected]</a>"
            },
            {
                "_id": "5aaa50a0ac40d32404c8bab7",
                "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2858595a684f45494144064b4745">[email protected]</a>",
            },
            {
                "_id": "5aa8ace3323eeb001414a2c5",
                "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9b1b0b389aea4a8a0a5e7aaa6a4">[email protected]</a>"
            },
            {
                "_id": "5aa86645323eeb001414a2af",
                "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3657545576515b575f5a1855595b">[email protected]</a>"

            }
    ]

The expected outcome should be 3.

Answer №1

To achieve this, you can utilize the reduce function.

This approach involves storing previous emails to track count increments.

var array = [{    "_id": "5aaa4f8cd0ccf521304dc6bd",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c7f7e666d64657e3f3e4c6b616d6560226f6361">[email protected]</a>"  },  {    "_id": "5aaa50a0ac40d32404c8bab7",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1063627a71787962232250777d71797c3e737f7d">[email protected]</a>",  },  {    "_id": "5aa8ace3323eeb001414a2c5",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7b0f9b6b9a4bfa2bb97b0bab6bebbf9b4b8ba">[email protected]</a>"  },  {    "_id": "5aa86645323eeb001414a2af",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771504071e1b161c371418180712051206021e071a121903591416">[email protected]</a>"  },  {    "_id": "5aa92c7d66c8820014813ed8",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d2a632c233e2538210d2a202c2421632e2220">[email protected]</a>"  }];

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

console.log(count);

Another method is by using the Set object.

  • Map the arrays of emails.
  • Initialize the Set object with the mapped array.
  • Obtain the count value using the size property.

var array = [{    "_id": "5aaa4f8cd0ccf521304dc6bd",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d3e3f272c25243f7e7f0d2a202c2421632e2220">[email protected]</a>"  },  {    "_id": "5aaa50a0ac40d32404c8bab7",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02717068636a6b70313042656f636b6e2c616d6f">[email protected]</a>",  },  {    "_id": "5aa8ace3323eeb001414a2c5",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="30571e515e4358455c70575d51595c1e535f5d">[email protected]</a>"  },  {    "_id": "5aa86645323eeb001414a2af",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cfeefecf5f0fdf7dcfff3f3ecf9eef9ede9f5ecf1f9f2e8b2fffd">[email protected]</a>"  },  {    "_id": "5aa92c7d66c8820014813ed8",    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b5c155a5548534e577b5c565a525715585456">[email protected]</a>"  }],
    mapped = array.map(e => e.email),
    set = new Set(mapped),
    count = set.size;

console.log(count);

Answer №2

If you need to organize your data based on a specific criterion, consider utilizing the groupBy function in lodash library. This method allows you to group elements together and easily determine the length of the resultant array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can I take to prevent Internet Explorer from caching my webpage?

After implementing Spring MVC for Angular JS on the front end, I encountered an issue where logging in with different user credentials resulted in incorrect details being displayed. This problem only occurred in Internet Explorer, requiring me to manually ...

Mastering ReactJs: The Ultimate Guide to Updating State Properties

I've been attempting to change the isSelected property for a specific row in my state data, but am finding that it's not updating. Can someone please offer guidance on the most effective approach to achieve this? var selecte ...

including a content tag into an input field within a template

I'm experimenting with the new html5 template tag to create a versatile form that can be used in various situations without relying heavily on javascript. Check out this fiddle to see what I have so far http://jsfiddle.net/684uH/ My objective is to ...

Displaying data in JSON format using CakePHP

I'm having difficulty formatting the content retrieved from my Controller as JSON in my view. Instead of displaying neatly like a typical JSON output, mine appears messy and unorganized. When I search for JSON online, I see outputs that look like thi ...

Unlocking the secrets of extracting dimensions from imported SVG components in nextJS

I am facing an issue with importing an SVG file as a component and trying to obtain its dimensions, but it keeps returning null. Can someone provide me with advice on how to resolve this? PS. When I try using getBBox(), it throws an error. Here is the co ...

implementing AJAX functionality in Laravel when a drop-down item is selected

Hello there, I am a newcomer to the world of coding and I'm currently learning Laravel for a personal project. My goal is to retrieve data from a database based on the selection made in a dropdown menu. Here's the code for the dropdown menu: < ...

What is the best way to adjust the value of largePageDataBytes in Next.js?

I am looking to modify the largePageDataBytes setting, despite knowing it may impact performance. I made an attempt in next.config.js with the following code: /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options h ...

Can JSON.parse be used on only a portion of an object in JavaScript?

Currently, I am facing an issue with a lengthy JSON file that I am fetching from a URL using https.request. Upon attempting to parse the string with JSON.parse, I encounter an "Unexpected end of JSON input" error. It appears that there is a limit to the ...

Disable checkboxes upon page initialization

I am working with a form that includes checkboxes. Whenever the page loads, clicking on the checkboxes automatically checks them. However, I am looking for a solution where the checkboxes are disabled or not clickable during the page load process. Once th ...

What is the reason border property does not transition effectively?

I am trying to remove the border property after a certain period of time (1 second) and make it smooth. Here is what I have attempted: var elem = $('div').css({'border-top':'6px solid #FC9A24', 'border-le ...

Unexpected behavior when merging objects containing arrays in jq

Struggling to merge multiple objects using jq? If MY_OBJECTS contains JSON objects with a single key each, you can combine them into a single array like this: $ echo ${MY_OBJECTS} | jq -s '.' ... Want to further combine these objects so that al ...

Refresh ng-repeat array after implementing filter in controller

I am currently facing an issue with updating my table view when changing a variable that filters an array. The filter is applied in the controller based on the values of a specific variable called columnFilter. However, the filter does not reapply to updat ...

Adding HTML content inside an iFrame at a specific cursor position in Internet Explorer

Does anyone know a method to insert HTML into an iFrame specifically for IE? I have been using execCommand insertHtml in Chrome and Firefox, but it doesn't seem to work in IE. I was able to paste HTML into a content editable div using pasteHTML, howe ...

Storing JSON data in SQL Server

Is there a way to eliminate spaces using the given query? The second input value (" DEF") and third input value ("GHI ") contain extra spaces. How can we remove these spaces? Here is the original query: SELECT * FROM openjson('[{"value":"12 ...

Managing errors through middleware functions

Currently, I've been studying node.js on and off. I came across this question: Middleware 1: app.use(function(req, res, next) { db.load(function(err, session) { if (err) { return next(err); } ... }); }); Middleware 2: app.u ...

Angular II slash avoiding Pipe

I am working on developing a customized pipe in Angular 2 that will handle the replacement of the backslash ('\') character in a given string. This backslash is commonly used to escape special characters. What I have accomplished so far: T ...

What are some strategies for retrying an Apollo Client query after a failure?

When working with Next.js server-side rendering (SSR), I often encounter a query failure on the first try due to the backend not being fully ready. In such cases, I would like to retry the fetch using ApolloClient. const PREVIEW = { query: MY_PREVIEW_ ...

Converting a Pandas dataframe to JSON format while excluding the index column

I am currently working on converting a dataframe into a specific JSON format. Below is an example of my dataframe: DataFrame name: Stops id location 0 [50, 50] 1 [60, 60] 2 [70, 70] 3 [80, 80] This is the desired JSON format I am aimi ...

Is Javascript Functioning Properly?

Similar Question: How do I determine if JavaScript is turned off? Can we identify whether javascript has been disabled and then redirect to a different page? I am currently working on a project using JSPs, where I have integrated various advanced java ...

HTML content that is produced through JSONP retrieval

Recently, I've been experimenting with the jQuery library and have found it to be quite useful. Lately, I've been delving into AJAX requests to fetch various information like weather updates, current downloads, and more, which has been going smoo ...