Generating arrays of duplicate elements in JavaScript

Let's say we have an array structured like this:

let arr = [{
    name: "Peter"
}, {
    name: "Peter"
}, {
    name: "John"
}, {
    name: "Peter"
}, {
    name: "Sarah"
}, {
    name: "John"
}]

The goal is to transform it into a new array that groups the duplicates together like this:

let dupArray = [
    [{
        name: "Peter"
    }, {
        name: "Peter"
    }, {
        name: "Peter"
    }],
    [{
        name: "John"
    }, {
        name: "John"
    }],
    [{
        name: "Sarah"
    }]
]

This process focuses on creating a new array by grouping the duplicate elements, not simply duplicating them.

Answer №1

Convert the array into a Map and retrieve the values:

const data = [{
  name: "Alice"
}, {
  name: "Alice"
}, {
  name: "Bob"
}, {
  name: "Alice"
}, {
  name: "Eve"
}, {
  name: "Bob"
}];

const duplicatesArray = 
    [...data.reduce((accumulator, current) => 
        accumulator.set(current.name , (accumulator.get(current.name) || []).concat(current)),
     new Map()).values()];

console.log(duplicatesArray);

Answer №2

let names = [{name: "Peter"},{name: "Peter"},{name: "John"},{name: "Peter"},{name: "Sarah"},{name: "John"}]

  let groupNames = function(array){
      // counts the occurrences of each name
      let countMap = {};
      for(item of array){
          if(countMap[item.name] !== undefined){
              countMap[item.name]++;
          }
          else {
              countMap[item.name] = 1;
          }
      }

      // create desired format
      let formattedArray = [];
      for(name in countMap){
          let occurrenceCount = countMap[name];
          let subArray = [];
          for(let i = 0; i < occurrenceCount; i++){
              subArray.push({ "name" : name });
          }
          formattedArray.push(subArray);
      }

      return formattedArray;
  }

  document.getElementById("result").innerHTML = JSON.stringify(groupNames(names));
<pre id="result"></pre>

The groupNames function first counts the number of occurrences of each name, then generates a new representation by adding objects with the corresponding names based on the counts. The naming convention is arbitrary.

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

Question about MongoDB Concurrency - Ensuring Atomicity with FindOne and FindOneAndUpdate operations

Before I proceed with coding, I kindly request your insights on a specific scenario I am trying to address. Despite reviewing numerous MongoDB documents and forums, I still seek clarity on how certain operations would be executed in my unique situation. ...

Is Javascript automatically generated by asp.net?

If I were to initialize a fresh VS project and paste the subsequent sample code into a freshly created page default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApplication1._default" %> <!DOCTYPE ...

transforming the fgetcsv output into customized JSON format

I have a file in .CSV format containing the following headers: Description, BusinessName, IsClient, IsVendor, AddressType, Business Address, IsGlobal. The first row includes: Contact1, Contact1, True, True, Business, 123 Fake St, False While the rest o ...

Encountering the error message: "TypeError [ERR_INVALID_ARG_TYPE]: The initial parameter should either be a string, Buffer instance, or Uint8Array."

Having trouble with the payment gateway API and subscription creation. Encountering an error that I can't seem to resolve even after debugging. Despite my best efforts, the error persists. The form and everything else seem to be in order, but the err ...

AngularJS is failing to properly register custom directives

Looking to enhance the SEO caching capabilities of my AngularJS website, I've embarked on implementing a couple of directives for custom page titles and descriptions. Incorporated within my app config (angular.module('website', [...'we ...

Brick-themed HTML/CSS elements drift away from each other

I'm currently designing an image collage for my website and attempted to use masonry for the layout. However, when I adjust the size of the blocks, they seem to drift apart, creating large gaps between each block. Any suggestions on how to resolve thi ...

How can I prevent dataTable resizing?

Is there a solution to prevent datatable resizing? For instance, when the default number of rows per page in the datatable is set to 10 rows. If you input 13 rows into the datatable, it will be divided into 2 pages - with 10 rows on the first page and 3 ro ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Accessing and assigning an ID to a particular line in a text file using JavaScript

I have a plain text document formatted as follows... Hello . world . . . . its me The code I am currently using to access the text file is as follows: <head> <script type="text/javascript"> function fetchTextFile(); </script> < ...

Is there a way to choose a mat option by pressing the tab key? It should function similarly to the enter button in a mat-autocomplete component in Angular

Is it possible to make the tab key select the mat option in a similar way to how the enter button works in mat-autocomplete for Angular 6? Currently, in the example URL provided, pressing enter selects the highlighted option, but I would like the same func ...

The error alert must be displayed directly beneath the specific box

When error messages occur in this code, they are displayed through an alert box. However, I would prefer to have the error message appear below the specific text box instead. This means that when I click on the submit button and a field is left empty, the ...

Using the innerHTML property to place an Img tag within a div element

I'm facing an issue with including multiple tags within a div using innerHTML. To better illustrate my problem, here's an example: var y = "jack.jpg"; var x = "Jack"; var f = "Hello world!"; document.getElementById("maindDiv").innerHTML += "< ...

Dealing with click events on layers with z-index positioning

In the map application I am developing, I have implemented 2 z-index layers. However, a problem arises when attempting to zoom in by clicking on these layers. The click handler is located on the lower z-index layer and I do not want it to execute when a co ...

Refresh gif without having to reload it in Internet Explorer 11

I'm attempting to create a feature where a gif restarts when clicked by the user, without needing to reload it (due to the heavy size of the gif which is preloaded for my application). The current code functions flawlessly on Chrome and other "modern ...

Utilizing ng-hide or ng-show with a select box dropdown option

Can select box options be hidden using the ng-hide directive? http://jsfiddle.net/cr4UB/ <div ng-app ng-controller="Controller"> <select ng-model="myDropDown"> <option value="one">One</option> <option va ...

Troubleshooting the Create Order Issue: Integrating PayPal Checkout with Smart Payment Buttons using React and Redux

Every time I attempt to process a payment, I encounter a 422 error: Unprocessable entity. The issue arises when I try to dynamically capture the purchased item details received from the redux store. I tried following this example (duplicate): PayPal Check ...

Issue encountered: An unexpected token = error appeared after updating from RN version 0.64.2 to 0.65.1

After upgrading from version 64.1 to 65.1 using the upgrade helper, I encountered an error that has been difficult to resolve. Even after updating node/npm to version 14.17 and trying various other solutions, I have not been able to fix this issue during ...

What discrepancies can be found concerning the initialization of char s[] and char *s?

When declaring a string using a string literal like this: char str[] = "hello"; or like this: char *ptr = "hello"; You can initialize ptr with str: ptr = str; //valid but not the other way around: str = ptr; //invalid This may seem confusing ...

Is it possible to enable tooltips to function through the innerHTML method?

Currently, I am utilizing the innerHTML attribute to modify the inner HTML of a tag. In this instance, it involves the <td></td> tag, but it could be applied to any tag: <td *matCellDef="let order" mat-cell [innerHTML]="order. ...

How to place an element in a specific location within the DOM using JavaScript

How can I position a created element in a specific place within the DOM using this code? Currently, it appends at the bottom of the page. var x = document.getElementById('options_10528_1'); var pos = document.getElementById('options-10528- ...