Detecting duplicate key values within a JSON array using Angular.js

I am seeking a solution in Angular.js to verify if duplicate key values exist within a JSON array. Below is a breakdown of my code:

 var result=[{
          "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8dac8b818d8580c28f8381">[email protected]</a>',
          "title":'hello',
          "start":'yes'
        },{
          "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e485a48389858d88ca878b89">[email protected]</a>',
          "title":'hello',
          "start":'yes'
        },{
          "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd9fbdcd6dad2d795d8d4d6">[email protected]</a>',
          "title":'ggggg',
          "start":'No'
        },{
          "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9cbb9c969a9297d5989496">[email protected]</a>',
          "title":'hel',
          "start":'No'
        },{
          "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f6d4f3f9f5fdf8baf7fbf9">[email protected]</a>',
          "title":'ggggg',
          "start":'No'
        }];
    if (result.length > 0) {
        angular.forEach(result,function(obj2){
            var data={'title':obj2.mname,'start':obj2.date};
            evtArr.push(data);
        })
    }

In this scenario, I need to ensure that before adding new data to evtArr, it checks for duplicates based on the key - email. If a value set belonging to a specific email (

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6afe8a3eba786a1aba7afaae8a5a9ab">[email protected]</a>
) is already present in evtArr, then the other one should be removed.

Answer №1

To create an object using array#reduce, use the email as the key and the object as the value. Extract all values from the object by utilizing Object.values().

var result=[{ "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e3c2e5efe3ebeeace1edef">[email protected]</a>', "title":'hello', "start":'yes' },{ "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="761736111b171f1a5815191b">[email protected]</a>', "title":'hello', "start":'yes' },{ "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b597b5c565a525715585456">[email protected]</a>', "title":'ggggg', "start":'No' },{ "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="197e597e74787075377a7674">[email protected]</a>', "title":'hel', "start":'No' },{ "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660426010b070f0a4805090b">[email protected]</a>',"title":'ggggg', "start":'No' }], output = Object.values(result.reduce((r,o) => { r[o.email] = Object.assign({},o); return r; },{})); console.log(output);

Answer №2

Here is a straightforward and clear solution for you.

To start, add the results to the resultFinal array only if the result with the same email hasn't already been added to that array.

let resultFinal = [];

result.forEach((resI) => {
  if (resultFinal.findIndex(resF => resF.email === resI.email) === -1) {
    resultFinal.push(result);
  }
});

Once you have the resultFinal array ready, use map to create objects containing only the title and start properties for each element.

resultFinal = resultFinal.map((resF) => {
  return {title: resultf.title, start: resultf.start};
});

I hope this explanation helps you understand the process better.

Answer №3

Give this code a try for easier understanding

var data = [{
                "email": '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6504250208040c094b060a08">[email protected]</a>',
                "title": 'hello',
                "start": 'yes'
            }, {
                "email": '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e2f0e29232f2722602d2123">[email protected]</a>',
                "title": 'hello',
                "start": 'yes'
            }, {
                "email": '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f4d6f48424e4643014c4042">[email protected]</a>',
                "title": 'ggggg',
                "start": 'No'
            }, {
                "email": '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4a384a3a9a5ada8eaa7aba9">[email protected]</a>',
                "title': 'hel',
                "start": 'No'
            }, {
                "email": '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb89ab8c868a8287c5888486">[email protected]</a>',
                "title": 'ggggg',
                "start": 'No'
            }];
            
            if (data.length > 0) {
                var newArray = [];
                
                for (i = 0; i < data.length; i++) {
                    var obj = {};
                    
                    obj.email = data[i].email;
                    obj.title = data[i].title;
                    obj.start = data[i].start;
                    
                    var distinctDate = newArray.filter(function(element) {
                        return element.email == data[i].email;
                    });
                    
                    if (distinctDate.length == 0) {
                        newArray.push(obj);
                    }
                }

            }

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

Issues with retrieving the subsequent anchor element using Jquery Slider

(Apologies for the lengthy post. I like to provide detailed explanations.) Just starting out with Jquery, trying my hand at creating a custom image slider from scratch. Got the slider working with fade effects using this code: Javascript: $(document).re ...

The results from utilizing Mongoose's text search feature are inaccurate and not matching the expected

Currently, I am in the process of developing a recipe blog website using Mongoose, Node.js, and Express. However, I have encountered an issue with the text search functionality not producing the desired output. In my Recipe.js schema, I have included spec ...

Using Ajax to update multiple text field rows with unique values

I have a question regarding utilizing Ajax to update the second text field based on the input from the first text field. I am looking to create multiple rows using a for loop, with each row having its own set of values. HTML <form style="text-align:c ...

Ordering tables according to the last column using jQuery

Despite trying various solutions provided in other discussions, I have been unable to get the table to display in descending order based on the Weight Score column. Here is a reference of the table: <table align="center" border="1px" cellpadding="5" id ...

"How to change the hover background of a select element in Chrome from its default setting to something else

Is there a way to remove the background color on hover and replace it with a different color? .drp-policydetails { border: 1px solid #dddddd; background-color: #ffffff; } <div className="form-group"> <select className="form-control drp-po ...

Populate a dropdown with values from a JSON object

There is a function in my code that retrieves JSON text from a specific website: window.onload = function httpGet() { var xmlHttp = null; var box = document.getElementById("http") //just for testing xmlHttp = new XMLHttpRequest(); xmlHttp. ...

During my JavaScript coding session, I encountered an issue that reads: "Uncaught TypeError: $(...).popover is not a function". This

Encountering an issue while trying to set up popovers, as I am receiving this error: Uncaught TypeError: $(...).popover is not a function. Bootstrap 5 and jQuery links are included in the code, but despite that, the functionality is still not operational. ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

Transform a two-dimensional array into a JSON object within the Laravel framework

Recently, I've been working on converting a two-dimensional array into a JSON object. Here is the current output produced by my controller: [ [ { "id": 1, "title": "V1", &q ...

Refresh the webpage content by making multiple Ajax requests that rely on the responses from the previous requests

I am facing a challenge where I need to dynamically update the content of a webpage with data fetched from external PHP scripts in a specific sequence. The webpage contains multiple divs where I intend to display data retrieved through a PHP script called ...

Setting the width of a div element dynamically according to its height

Here is a snippet of my HTML code: <div class="persoonal"> <div class="left"></div> <div class="rigth"></div> </div> This is the CSS code I have written: .profile { width: 100%;} .left { width: 50%; float: le ...

What is the best way to efficiently query a substantial dataset using Node.js in an asynchronous fashion?

I need to extract data from a mysql database by fetching 10 rows at a time until I reach 400k rows. To achieve this asynchronously, I am using recursion as shown in the code below: var migrate = function(offset, size) { Mysql.query(query, [offset, size] ...

Getting data from an API with authorization in Next.js using axios - a step-by-step guide

click here to view the image user = Cookies.get("user") I'm having trouble accessing this pathway. I stored user data, including the token, using cookies. Please assist me with this issue. ...

Mapping objects with nested objects using ObjectMapper

I'm facing an issue with mapping a JSON response that contains an array. The mapping process is throwing an error, and I need help on how to handle this type of JSON structure. { "total":10, "count":10, "start":0, " ...

Dropzone is encountering an issue with uploading photos: The upload path seems to be invalid

Despite thoroughly checking the path settings in my code, the error message persists when I attempt to upload photos using Dropzone. It seems to be indicating a problem with the upload path. What could be causing this issue? I am currently in the process ...

React App stalled due to continuously running function

In this section of my React app, the createBubbles function is functioning properly. However, I am encountering an issue where the entire app freezes when navigating to another page after visiting this one. The console displays the following errors and de ...

Tips on waiting for an event to be processed during a Protractor end-to-end test

I have a straightforward AngularJs 1.4.8 Front-End: https://i.stack.imgur.com/2H3In.png After filling out the form and clicking the OK button, a new person is added to the table. The form resides in the addingPersonController, while the table is control ...

Node.js application with decoupled Redis client

In my node.js app, I am utilizing Redis for user caching. Once a user logs in, their information is cached and accessed on subsequent requests to determine their access level. This allows the client to receive personalized information and views based on th ...

Alter the color of the dropdown background when it is changed

Currently, I am utilizing the Semantic UI React CSS library and find myself in need of changing the background color of dropdowns once an option is selected. to <Dropdown placeholder='Name' selection search options={names} className=&a ...

The error message encountered with React Easy DatePicker is: "Uncaught ReferenceError: process is not defined."

I am attempting to integrate the stylish DatePicker from https://www.npmjs.com/package/sassy-datepicker?activeTab=readme Here is my implementation : import DatePicker from "sassy-datepicker"; function App() { const [date, setDate] = useSta ...