Tips for locating identical values within a JavaScript map

I am faced with a challenge involving a JavaScript map where all the values are the same. I need to create a new map for each unique value in the original map, storing key-value pairs that match. Essentially, I aim to create new maps based on the values present in the original map, with each value generating its own dedicated map where the keys remain the same.

//The mainMap is dynamically generated based on data retrieved from an API call
const mainMap = new Map();
//Populate the mainMap with data received from the API
//Sample data below; actual data is dynamic
mainMap.set(1, 'a');
mainMap.set(2, 'b');
mainMap.set(3, 'c');
mainMap.set(4, 'a');
mainMap.set(5, 'c');
mainMap.set(6, 'b');
mainMap.set(7, 'c');
mainMap.set(8, 'a');
mainMap.set(9, 'c');
mainMap.set(10, 'c');
mainMap.set(11, 'a');
mainMap.set(12, 'c');
mainMap.set(13, 'a');
mainMap.set(14, 'c');
mainMap.set(15, 'c');
mainMap.set(16, 'e');
mainMap.set(17, 'f');
......

//Identify keys with the same values and create new maps accordingly
const newMap1 = new Map();
newMap1.set(1, 'a')
newMap1.set(4, 'a');
newMap1.set(8, 'a');
newMap1.set(11, 'a');
newMap1.set(13, 'a');

const newMap2 = new Map();
newMap2.set(2, 'b');
newMap2.set(6, 'b');

const newMap3 = new Map();
newMap3.set(3, 'c');
newMap3.set(5, 'c');
newMap3.set(7, 'c');
newMap3.set(9, 'c');
newMap3.set(10, 'c');
newMap3.set(12, 'c');
newMap3.set(14, 'c');
newMap3.set(15, 'c');

const newMap4 = new Map();
newMap4.set(16, 'e');

const newMap5 = new Map();
newMap5.set(17, 'f');


......



Thank you in advance for your help!

I have attempted to split the main map into smaller sub-maps by identifying matching values, but have not been successful so far.

Answer №1

Here is a method for creating an object named res that includes maps for variables a, b, c, e, and f. Using a simple "map to object" conversion, I have displayed each map's content as if it were an object in the console output below:

Object.fromEntries(map.entries())

const mainMap = new Map();
//Populate map with data
//Sample data inserted from API call
//Actual data is dynamic
mainMap.set(1,'a');
mainMap.set(2,'b');
mainMap.set(3,'c');
mainMap.set(4,'a');
mainMap.set(5,'c');
mainMap.set(6,'b');
mainMap.set(7,'c');
mainMap.set(8,'a');
mainMap.set(9,'c');
mainMap.set(10,'c');
mainMap.set(11,'a');
mainMap.set(12,'c');
mainMap.set(13,'a');
mainMap.set(14,'c');
mainMap.set(15,'c');
mainMap.set(16,'e');
mainMap.set(17,'f');

const res={};
mainMap.forEach((v,k)=>(res[v]??=[]).push([k,v]));
Object.entries(res).forEach(([k,arr])=>
  res[k]=new Map(arr))

// Display the results 
Object.entries(res).forEach(([k,map])=>{
 console.log(k);
 console.log(Object.fromEntries(map.entries()));
});

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

Repeatedly encountering identical values in delayed for loop

I can't figure out why my delayed for loop is consistently giving me a "-1" as the result. for (var i = 5; i > 0; i--) { setTimeout(function() { console.log(i) }, i * 1000) } (I adjusted my variable to be 5) ...

Retrieving live information from an API in order to populate a specific route

Utilizing the contents of two crucial files to extract data from separate APIs, here is my simplified example: poloniex.js const Poloniex = require('poloniex-api-node') const poloniex = new Poloniex() async function obtainExchangeData() { po ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

What is the best way to ensure that the texture is properly positioned when replacing textures in gltf format using Three.js?

Trying to dynamically change the texture of a glTF model using the `THREE.TextureLoader`, I successfully changed the color as expected. However, the texture pattern appeared distorted. Exploring web graphics for the first time, I modified a 3D model viewe ...

Post request in ExpressJS fails to redirect user after submission

My current project involves developing a web application using NodeJS and ExpressJS. One issue I am encountering is with the login functionality on my website. After filling out the login form, the user's credentials are sent via a post request to the ...

How can ReactJS retrieve URLs from a database to upload images?

Hey everyone, I'm relatively new to ReactJS and nodeJS for frontend and backend development. Recently, I received some assistance in displaying all the outputs of a table in a select form, but now I'm facing difficulties with images. My colleagu ...

Provide an instance of mockClient for AWS SQSClient in a TypeScript class

I'm currently working on unit testing a piece of code that relies on a constructor with an SQSClient object for interacting with an sqs queue. To write effective unit tests, I need to mock the client so that I can test the code without actually access ...

Tips for eliminating redundancy in $scope manipulation code within multiple controllers using angularJS

Apologies if this question seems trivial, but I am just getting started with angularJS. I have created two controllers: seekerController and wizardController... Within the wizardController, there is a Scope object called chat, which is being manipulated ...

During the Jasmine test, an error was encountered when trying to call a factory function that includes both a local and another function. The error message displayed

I have a factory with two functions and two local methods. I have written a Jasmine test case in which I expect the local method updateDetails and the factory function SavePref.savePref to be called when SavePref.saveDetails(values, prop); is invoked, as s ...

Locate the class and execute the function on the existing page

Stepping outside of my comfort zone here and I'm pretty sure what I've come up with so far is totally off. Ajax is new to me and Google isn't making things any clearer, so I was hoping someone more knowledgeable could assist! Basically, I w ...

Fluid carousel and dynamic loading

Currently, I am experiencing an issue with the Liquid Slider while using ajax, specifically related to height. Below is the script I am using: var api2 = $.data( $('#slider-7')[0], 'liquidSlider'); $.ajax({ complete: function( ...

Interactive Notification System with MySQL, AJAX, and PHP

Seeking assistance for code conversion from async ajax to sync ajax. The current code is causing system lag after 20 minutes of inactivity. Likely issue resides within the code snippet provided below. function addmsg20(type, msg, data) { $('# ...

Expanding list selection with jQuery_hover effect

I have devised the following code. HTML <ul class="treatment-menu"> <li>Menu always visible</li> <ul class="nav-child"> <li>Hidden sub menu</li> </ul> </ul> Hover function $(&a ...

"Upon requesting three gltf files, the response was found to

Currently, I am utilizing the GLTF loader for the purpose of importing a custom model into my scene. Within my codebase, there exists a class called Spaceship.js that manages the loading of the model. // Spaceship.js import { GLTFLoader } from 'thr ...

Creating personalized labels with Vue.js and Element UI radio button components

When using Element UI radio buttons on a form, I am attempting to personalize the label for each selection. Each radio button includes a prop called "label" where I can input my label text successfully. The problem arises when I need to apply a different s ...

Accessing or saving a PDF document for print directly from an iPhone using JavaScript

Is there a way to access or download a PDF file on an iPhone using JavaScript in a web application? I have tried using window.open(src); and it works on Android and all desktop operating systems, but not on iPhone. I need to be able to generate a PDF fil ...

The result of combining two JavaScript variables

When I multiply a variable by 2 and assign the value to another variable, why do I get 0? My goal is to toggle the visibility of blocks every time a button is pressed. Oddly enough, it works when I use count++ * 2. For code reference, please refer below: ...

(Critical) Comparing AJAX GET Requests and HTTP GET Requests: identifying the true client

When a typical GET request is made through the browser, it can be said that the browser acts as the client. However, who exactly serves as the client in the case of a GET request via AJAX? Although it still occurs within the browser, I am intrigued to delv ...

What is the best way to modify a CSS property using logical operators in JQuery?

If an element with the class ".has_padding" does not have any text content, it should be set to "display:none;". However, those elements with text inside should remain visible. Below is some code where I have styled the elements to demonstrate the issue. ...

Tips for utilizing ngDoc comments in routeConfig

I am currently working on documenting my Angular WebApp using ngdocs and grunt. I am facing a challenge with the complexity of my routing system and feel that it needs more attention in terms of documentation. Is there a way to document the route configur ...