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 is the most efficient way to retrieve the current user's ID within Loopback?

Given the instability and deprecation of loopback.getCurrentContext(), what strategies can I use to accurately identify users when they interact with API endpoints? Is it feasible to include the token ID in the request payload for verification purposes? H ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

Saving the initial state value in a variable in Vue.js is a crucial step in managing and

My dilemma involves an object in the Vuex store containing data that I need to utilize within a component. I have successfully accessed the data using a getter in the component. However, I am facing a challenge in preserving the initial value of this objec ...

Sorting columns using custom conditions in DataTables

Within a PHP project I am working on, I have encountered a need to organize a specific column using a custom condition or order rather than relying on the default ordering provided by DataTable (ascending or descending). The project involves four distinct ...

obtain every potential substring in sequence

After exploring various methods to find possible substrings, I attempted an approach in PHP which can be found here. However, I have specific requirements for generating substrings. For example, if the input string is 'ABCDE', the desired combin ...

How can I use Three.JS TWEEN to animate object movement between two objects at a

I'm working on a game where an object moves towards other objects. new TWEEN.Tween( object.position ).to({ x: Math.position = pointX, z: Math.position.z = pointZ }).easing( TWEEN.Easing.Linear.None).start(); However, I've encountered a pr ...

When the page is loaded, ensure a condition is met before displaying a modal pop-up using AngularJS

Just starting out with AngularJS and looking to implement a modal pop up? I've tried using the modal on button click from the Angular dialog demo tutorial. Now, I want to show the pop up based on a condition when the page loads. The idea of automatic ...

Is there a way to retrieve a value from localStorage and use it to automatically set the selected option in a UL-based dropdown list upon page load

I have implemented a unique UL-based dropdown list that I discovered here (specifically the third model) as the foundation for a role-based selection box for my users. To enhance user experience, I am storing their role selection in localStorage so they do ...

Steps to generate a newline-separated JSON-lines file from a collection of Python dictionaries

To meet the requirements for online prediction on Google Cloud AI platform, I am working on creating a JSON-lines file containing my data. My data is currently stored as a list of dictionaries, structured like this: data = [{'values': [0,1,0], ...

Text located in the bottom right corner of the window with the use of JavaScript

Is there a way to replace text at the bottom right of the window, as opposed to the page, so that it remains fixed in the corner of the window? I'm looking to create a "share" link that is always visible. ...

When clicked, the menu disappears successfully with the "show" functionality, but unfortunately, the "hide" feature is not working as intended

Within my menu, I have a section for portfolios that transforms into a dropdown on desktop hover and mobile click. The issue arises on mobile devices where the first click displays the menu correctly, but subsequent clicks do not trigger any change. I att ...

Tips on configuring a hidden input field to validate a form

I am currently attempting to create a blind input field using PHP that will validate if the input field is empty. If it's not empty, the message set up to be sent will not send. However, I have encountered several issues with the placement and wording ...

Tips for personalizing Twitter Bootstrap popover concealment animation

Currently, I am interested in creating a unique hide animation for my popover. Instead of directly modifying bootstrap.js, I would like to implement my own custom code. $.fn.popover = function (option) { return this.each(function () { ...

Ways to retrieve the identifiers of every child node UL element within a UL container

I am struggling with a basic question related to HTML structure. Here is the code snippet I am working with: <ul> <li> <ul class=t2 id=15> <li class='item'>a<span class='val'>b</ ...

Using React Router can sometimes lead to an issue where the React components are

My server side rendering is set up for performance, but I am encountering discrepancies between the client and server renderings. The client initially renders <!-- react-empty: 1 --> instead of components, which leads to a different checksum. As a re ...

Using jQuery to move a div to a specific location on the page

Is there a way to translate the position of div x and y using Jquery that is compatible with all browsers, such as IE 7, IE8, IE9, and IE10? I have attempted the following: <div id="s1" style="-ms-transform:translate(159,430)"> hello ...

Tips on incorporating Angular ng-include

As a newcomer to AngularJS on an Express Framework, I am facing an issue with loading HTML pages as includes. Although my routing in Angular is set up correctly and functioning well, when I try to use ng-include in my HTML pages, it results in a loop and t ...

How can we assign priority to the child element for detection by the "mouseover" event in jQuery?

Can you help me figure out how to make the "mouseover" event prioritize detecting the child element over its parent? This is the jQuery code I've been using: <script> $(function() { $("li").mouseover(function(event){ $('#log&a ...

Prevent the Icon in Material UI from simultaneously changing

I'm working on a table where clicking one icon changes all icons in the list to a different icon. However, I want to prevent them from changing simultaneously. Any suggestions on how to tackle this issue? Code: import React from 'react'; im ...

Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it: executeHelloWorldBeanServiceWithPathVariable(name){ console.log("name coming from here"+name); retu ...