Adding the number of occurrences to duplicates in a string array using JavaScript

Looking to append a count to duplicate entries within a string array. The array in question contains duplicates, as shown below.

var myarray = ["John", "John", "John", "Doe", "Doe", "Smith", 
               "John", "Doe", "Joe"];

The desired output should be:

var newArray = ["John - 1", "John - 2", "John - 3", "Doe - 1", 
                "Doe - 2", "Smith", "John - 4", "Doe - 3", "Joe"];

Seeking the most efficient method to achieve this transformation.

Answer №1

Here is a solution that involves utilizing two iterations of Array.map():

var map = {};
var count = myarray.map(function(val) {
    return map[val] = (typeof map[val] === "undefined") ? 1 : map[val] + 1;
});

var newArray = myarray.map(function(val, index) {
    if (map[val] === 1) {
        return val;
    } else {
        return val + ' - ' + count[index];
    }
});

In the first iteration, each unique item's frequency is calculated and stored in an object, creating an array with current frequencies of items.

The second iteration adds the frequency count to items that appear more than once.

For a demonstration, see http://jsfiddle.net/alnitak/Z4dgr/

Answer №2

similar to this

let occurrences = {}, freshArray = [];

// first run, count occurrences
for (let index = 0; index < givenArray.length; index++) {
   let element = givenArray[index],
       currentCount = occurrences.element;

   if (!currentCount) {
      currentCount = 1;
   } else {
      currentCount++;
   }

   occurrences[element] = currentCount;

   element = element + " - " + currentCount;
   freshArray.push(element);
}

// Revert changes for elements that occur only once
for (let index = 0; index < givenArray.length; index++) {
   let element = givenArray[index],
       currentCount = occurrences.element;

   if (currentCount === 1) {
      freshArray[index] = element;
   }
}

Note that I chose to use straightforward javascript for clarity and ease of understanding. Keep in mind that looping through the array twice may not be efficient for large datasets.

This code snippet has not been tested, but a similar approach should yield the desired results.

Answer №3

Here is a script that calculates the count of duplicate values in an array:

var myarray = ["John", "John", "John", "Doe", "Doe", "Smith", 
           "John", "Doe", "Joe"];
var values = {}, newArray = [];
for (var i = 0; i < myarray.length; i++) {
    if (typeof values[myarray[i]] === 'undefined') {
        values[myarray[i]] = 1;
    } else {
        values[myarray[i]] += 1;
    }
}
for (var i = 0; i < myarray.length; i++) {
    if (values[myarray[i]] > 1) {
        newArray.push(myarray[i] + ' - ' + values[myarray[i]]);
    } else {
        newArray.push(myarray[i]);
    }
}

Thank you for considering this solution!

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

Managing data in React using the useState hook

I need assistance in enhancing the state without causing any overwrite. Presently, whenever a new value is added, it replaces the existing array. My objective is to utilize useState and incorporate the form value. import {useState} from 'react'; ...

Pass a parameter to an AJAX request in order to retrieve data from a JSON file that is limited to a specific

I am working with a JSON file named example.json, structured as follows: { "User1": [{ "Age":21, "Dogs":5, "Cats":0 }], "User2": [{ "Age":19, "Dogs":2, "Cats":1 }] "User3 ...

When the clearInterval function is invoked - either when the timer is modified or when the rendering is detached from the setInterval it is linked to

As a new React developer, I've come across a problem that has me stuck. Does the setInterval associated with a specific render get cleared automatically? import React, { useState, useEffect, useRef } from "react"; import ReactDOM from ...

Trouble with uploading images to folder using PHP and AJAX is causing confusion

I'm having trouble uploading a photo using ajax and php. Despite following advice from other sources, I can't seem to make it work. Is there anything in my code that appears to be incorrect? The ajax request seems to go through successfully, so ...

While everything ran smoothly on my local machine, the app crashed on Heroku as soon as I integrated express-handlebars into the

After adding this code to the app, it started crashing on Heroku servers. Interestingly, removing these codes resolved the issue and the app worked perfectly on Heroku. However, the app works fine with these codes when tested locally. const exphbs = req ...

I've noticed that every time I use the simple-encryptor npm to encrypt something, the output is always different

Can you assist me in solving this issue? var key = 'real secret keys should be long and random'; // Generating an encryptor: var encryptor = require('simple-encryptor')(key); var encryptedText = encryptor.encrypt('testing') ...

Submitting several documents using PHP

Here is the HTML code I have: <p><input type="file" name="file[]" id="file" /></p> <p><input type="file" name="file[]" id="file" /></p> <p><input type="file" name="file[]" id="file" /></p> <p>< ...

Troubleshooting problem with Angular Materials' md-datepicker not displaying correctly in wide browser windows

While using the md-datepicker component in my application, I noticed that it does not display properly on larger browser widths. It only seems to work as expected on small and x-small viewports. Please refer to the attached screenshot for reference. This ...

Attempting to transmit information to database using AJAX in the context of CodeIgniter

I'm having some trouble with my AJAX setup. It doesn't seem to be posting any data to the database, despite trying various solutions I found online. That's why I've turned to this platform for help. When testing in Postman and sending ...

Focus issue with MUI Custom Text Field when state changes

Currently, I've integrated the MUI library into my React Js application. In this project, I'm utilizing the controlled Text Field component to establish a basic search user interface. However, an unexpected issue has surfaced. Following a chang ...

Is the × symbol added from JavaScript not able to be clicked on?

In my javascript code, I have added HTML content dynamically using the following method: var response = { message: "sample messsage" }; $('#main-content').append( '<div class="alert alert-danger alert-dismissable">'+ & ...

Retrieving an element from a nested array in MongoDb

I need help with the format for a query to remove an element (with an _id) from an array of arrays in Mongo. After checking the documentation, I couldn't find a solution that matches my scenario. Here is the link to what I was looking at: https://www ...

AJAX isn't quite cooperating - it seems that only the error callback is getting

Even though I have specified both success and error callbacks, the error callback is being triggered even when the status code is 200. In addition, I am also making a curl call to another php file within registry.php. This is what I have attempted: $.aj ...

A Beginner's Guide to Duplicating Bootstrap Containers in Jade

I am working with JSON data that is being transmitted from an Express and Mongoose Stack to be displayed on the user interface created in Jade. I am wondering which Jade Construct I should use to loop through a Bootstrap Container of col-md-4 using Jade s ...

What is the best method for implementing pagination in Larvael with React using Inertia?

Is there a way to paginate in react using inertia with laravel? When pulling paginated data, I use the following code: $contacts = Contact::orderBy('name', 'asc')->paginate(10); return Inertia::render('Contacts/index', [ ...

Deactivating the class from a button

On my website, I have 3 buttons that represent different product categories. The initial state of the page should load with the "All Products" button having an active class. However, when clicked, this active class should be removed from the "All Products" ...

Mongoose: No documents are being returned by the .find() method

UPDATE : Similar question posted here: Trouble with Mongoose find() method I'm still new to working with nodejs and nosql databases. Today, I am building an API that retrieves data from my user collection which currently has two entries : The issue ...

Spooky results displayed on website from NightmareJS

Is there a way to display the output from nightmareJS onto a webpage when a button is clicked using HTML, CSS, and JS? This is my nightmareJS code: var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: false}) nightmare .go ...

How can the formatResult and formatItem options enhance the functionality of JQuery Autocomplete?

I'm a bit puzzled here - can someone explain what the formatResult and formatItem functions do in the JQuery Autocomplete plugin? I have a function that returns a comma-separated string from Django, but I'm having trouble getting my autocomplete ...

Issue with CSS: Dropdown menu is hidden behind carousel while hovering

I'm struggling with adjusting the position of my dropdown list. It keeps hiding behind the carousel (slider). When I set the position of the carousel section to absolute, it causes the navbar to become transparent and the images from the carousel show ...