Find the total number of duplicate elements in a JavaScript array

I'm using an ajax call to retrieve values from a JSON structure and pushing them into a JavaScript array with .push for each iteration. However, I have multiple instances of the same value (e.g. person's name) in the array and I want to count the number of identical names and remove duplicates.

The ultimate aim is to create a chart displaying each person's name along with how many times they appear in the array.

Here is my current code:

var arr = [];

$.each(data.d.results, function (a, data) {
        $.ajax({
            url: "http://helpdesk.monjasa.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests(" + data.RequesterId + ")/CreatedBy",
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            success: function (data2) {
                $.ajax({
                    url: "http://helpdesk.monjasa.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests(" + data.AssignedToId + ")/AssignedTo",
                    headers: {
                        'accept': 'application/json;odata=verbose',
                        'content-type': 'application/json;odata=verbose'
                    },
                    success: function (data3) {
                        $(".inner").prepend('<p>' + data.Request + ' <br>Submitted by: ' + data2.d.Name + '<br>Assigned to: ' + data3.d.Name + ' | Due in: ' + data.DueInDays + ' day(s)</p>');
                        arr.push(data3.d.Name);
                        console.log(arr);
                    }
                });
            }
        });

Does anyone have any suggestions on how I can accomplish this task?

Answer №1

Perform a calculation on the counts and add to an array only if it is not already present.

let namesArray = [];
let countsArray = [];
$.each(data.d.results, function(index, value) { 
    $.ajax({
        url: "http://example.com/data/"+value.RequesterId+"/info",
        headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
        success: function(user){ 

            $.ajax({
                    url: "http://example.com/data/"+value.AssignedToId+"/info",
                    headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
                    success: function(assignedUser){

                            $(".output").prepend('<p>'+value.Request +' <br>Submitted by: '+user.d.Name+'<br>Assigned to: '+assignedUser.d.Name+' | Due in: '+value.DueInDays+' day(s)</p>');    

                    let nameIndex = namesArray.indexOf(assignedUser.d.Name);
                    if(nameIndex === -1) {
                            namesArray.push(assignedUser.d.Name);
                            countsArray.push(1);
                            console.log(namesArray);
                    }
                    else {
                            countsArray[nameIndex]++;
                    }

                    }  
                });

    }  
});

Answer №2

A simple method to identify duplicates is by creating an object and loading the data into it, like so:

// Example array:
var numbers = [3, 3, 4, 5, 5, 4, 3, 2, 1, 1, 2, 3, 3, 2, 2];

// Counting occurrences
var count = {};
for (var i = 0; i < numbers.length; i++) {
  var num = numbers[i];
  if (count[num] === undefined) count[num] = 0;
  count[num]++;
}

console.log(count);

Answer №3

Behold the power of this code snippet

    function calculateOccurrences(arr) {
        var index = arr.length, // variable for iteration
            result = {}; // object to hold results
        while (index) result[arr[--index]] = (result[arr[index]] || 0) + 1; // count occurrences
        return result;
    }

    function getOccurrenceCount(word, arr) {
        return calculateOccurrences(arr)[word] || 0;
    }

    getOccurrenceCount('Lorem', yourArr);

Answer №4

Create a new object to store the names of individuals and how many times they occur.

var peopleArray = [], nameOccurrences = {};

Within your success callback function, include:

success: function (data) {
    var personName = data.details.Name;
    $(".inner").prepend('<p>' + data.Request + ' <br>Submitted by: ' + data2.details.Name + '<br>Assigned to: ' + data3.details.Name + ' | Due in: ' + data.daysToDue + ' day(s)</p>');
    if (personName in nameOccurrences) nameOccurrences[personName]++;
    else peopleArray.push(personName), nameOccurrences[personName] = 1;
}

To display the names and their occurrences, use the following code:

for (var individual in nameOccurrences) console.log(individual + ': ', nameOccurrences[individual]);

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

Copying a class and adding the second item in the duplicated class

I have been working with an ajax function to retrieve names from the database. The issue arises when there are multiple names returned - I split them and then attempt to clone the first class in order to display the additional names. However, this proces ...

Is it possible to execute a Google Script on the last row of a spreadsheet exclusively

I have an email script that is functioning correctly, but I only want it to run through the last row with data in it. If there is no data in a row, then I do not need the script to run for that specific row. How can I modify the example script below to ref ...

Troubleshooting the Challenge of Adding Items to Cart Automatically in Magento

I am currently working on developing an ajax script that will enable users to add customizable items to their shopping carts. The script I have created is as follows: require_once('app/Mage.php'); umask(0); Mage::app(); error_reporting(E_ALL); ...

Begin the API server along with the React server for your React application

I'm currently working on my first React app, and I'm facing a challenge in getting both the API and the React server to start simultaneously. For client routes, I am using react-router. In a previous project, I utilized Express for setting up th ...

How to avoid an additional carriage return in Internet Explorer when editing a Textarea?

In Internet Explorer, we are facing an issue with a multiline textarea. After setting the content using JavaScript and checking it, everything appears correct without any additional carriage returns in the textarea: document.getElementById( 'text-ar ...

Utilizing the NODE_ENV variable in a Windows 10 npm script

I have integrated webpack into a Typescript project. Following a helpful tutorial, I created 3 separate webpack configuration files: webpack.common.js webpack.production.js webpack.development.js In the tutorial's package.json, the "scripts" sectio ...

Slide feature in Drupal Views allows you to create dynamic

This is the design I currently have: https://i.stack.imgur.com/P6spc.jpg For example, when you click on the "Structure" header, it opens up the contents and shows an image. I have created a content type and installed Views. I have separated the image, h ...

Testing for expressjs 4 using Mocha revealed unexpected behavior when attempting to spy on a function called within a promise. Despite setting up the

I have encountered a situation with some test cases structured like this: it('does stuff', function(done) { somePromise.then(function () { expect(someSpy).to.have.been.called done() }) }) When the assertion in a test case fails, it ...

Tips for Uploading Large Images to Backend API in Next.js

As I work on building my portfolio using NextJS, I encountered an issue with the Project Functionality. When converting images to base64 and sending them to an API for uploading on Cloudinary, everything runs smoothly as long as the total size of the req ...

What could be causing me to see an empty page when trying to use Django_ajax in conjunction with Django?

I am new to django and I attempted to follow the instructions on GitHub. However, when I ran the code, I only saw a blank page. Here is my code: views.py from django.shortcuts import render from django_ajax.decorators import ajax @ajax def AjaxView(reque ...

WordPress posts dynamically load additional content

I attempted to implement a method for loading more posts using ajax without relying on plugins. Despite researching online and on stackoverflow, I was unable to find a solution that works for me. My goal is to have the flexibility to use this code in vario ...

Steps for refreshing a JavaScript function responsible for generating a table

Within the code snippet provided, there is a click event attached to a table row. Upon clicking a row, the script extracts the id value from the first column and triggers a REST call. Subsequently, a new table is constructed using a third-party function ca ...

The mystery of the Accordion Effect: A Next.js/React.js issue where it slides up but refuses to

After implementing a custom accordion using next.js, I encountered an issue where the slide animation worked successfully when moving up and out upon clicking the button. However, when trying to move it back down into the content, it did not animate as exp ...

Show a loading indicator similar to a browser's loading animation during ajax requests

For example, if you go to your Facebook wall and scroll to the end of the page, Facebook will asynchronously load more wall posts. Alternatively, clicking on an image in a wall post will also trigger asynchronous loading of the image dialog with comments a ...

When you hit the enter key in a text input field in JavaScript, it triggers a specific function

http://codepen.io/abdulahhamzic/pen/YqMQwB Is there a way to make it so that when I hit the enter key on a text input, it triggers a specific function? I attempted to achieve this using the following code: <input type="text" onkeypress=" ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Issues arise with routing when specific route parameters are implemented

After setting a route parameter in my browser URL, I encountered errors with the routing of the public folder (which contains my CSS, JS, etc.). The app's structure is as follows: app | |-- public | └-- css | └-- profile.css | |-- ...

The onMessage listener in Chrome consistently returns an 'undefined' response

My latest project involves creating a simple chrome extension that utilizes message passing. The goal of the extension is to listen for messages from a specific website (in this case, localhost:8080/*) and respond with a simple "Bye". To test this function ...

Remove the pop-up using its unique identifier, element, or style class

I recently launched a free hosting site, but I'm encountering an issue where an ad for the site keeps appearing upon loading. I need to find a way to remove the specific rows that contain this ad. Specifically, I want to delete the ****BOLD**** rows, ...

Error message displayed in Ajax jQuery shows '[object Object]'

There seems to be an issue with this code on certain computers. I have a basic AJAX call set up to display a list of batches in a select tag. function show_batch(class_id,batch_id){ if(class_id){ $.ajax({ url:root_path+"module/fee_ ...