Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once.

While I am aware of options like forEach or for..of for looping, I'm struggling to figure out how to avoid duplicate pairs efficiently.

shapes.forEach((shape1, shapeId1) => {
    shapes.forEach((shape2, shapeId2) => {
        // processing each pair multiple times
    });
});

Answer №1

To start, my recommendation would be to convert the Map into an array of its entries:

const entryArray = Array.from(shapes.entries());

After that, you have the choice to iterate through pairs using either a traditional for loop:

console.log("FOR LOOP");
for (let i = 0; i < entryArray.length; i++) {
  const [shapeId1, shape1] = entryArray[i];
  for (let j = i + 1; j < entryArray.length; j++) {
    const [shapeId2, shape2] = entryArray[j];
    console.log(shapeId1, shapeId2);
  }
}

Alternatively, you can use the functional forEach array methods:

console.log("FOREACH");
entryArray.forEach(([shapeId1, shape1], i) =>
  entryArray.slice(i + 1).forEach(([shapeId2, shape2]) => {
    console.log(shapeId1, shapeId2);
  })
);

In both cases, duplicates are avoided by ensuring the inner loop only iterates over elements that come after the index of the outer loop. Regarding your types for Shape and id, assuming this structure:

interface Shape {
  area: number;
}

const shapes: Map<string, Shape> = new Map([
  ["a", { area: 1 }],
  ["b", { area: 2 }],
  ["c", { area: 3 }]
]);

The provided code will produce the following results:

FOR LOOP
a b
a c
b c
FOREACH
a b
a c
b c

As showcased, unique pairs are obtained. I hope this explanation aids you in your endeavors! Best of luck.

Link to code

Answer №2

To avoid processing two pairs, you can utilize two for loops with an index and initiate the nested iteration from the main index + 1.

const numbers = [1,2,3,4];


for (let x = 0; x<numbers.length-1; x++) {
  for (let y = x+1; y<numbers.length; y++) {
    console.log(`${numbers[x]} - ${numbers[y]}`)
  }
}

Answer №3

To find unique pairs in a collection of shapes, utilize a Set with the two indexes:

let pairIndexes = new Set();

shapes.forEach((shape1, shapeIndex1) => {

    shapes.forEach((shape2, shapeIndex2) => {

        if (pairIndexes.has(`${shapeIndex1}-${shapeIndex2}`) || pairIndexes.has(`${shapeIndex2}-${shapeIndex1}`)) return;
        pairIndexes.add(`${shapeIndex1}-${shapeIndex2}`);

    });

});

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

Modifying the input's value dynamically alters the selection choices in Vuetify

Choose the First option Fpo, when you select the first item, the first object in the list is assigned to the variable test. I have used test.name as a model for that input field. Strangely, when I try to modify the input field, the select option also chang ...

"Encountered a problem when trying to access properties within a

Struggling to access properties of a nested object in TypeScript while using Angular, I encountered the following error: Object is possibly 'undefined'. Here is the code snippet: export interface Address{ city?: string; neighborhood?: string; } ...

RadAjaxNamespace is not found within the codebase

While testing the application on my development machine, I encountered an error message in the browser debug console stating "RadAjaxNamespace is not defined". Interestingly, this error does not appear when accessing the production server. Upon comparing t ...

IE may not support the use of XMLHttpRequest with the POST method

When interacting with a server through an XMLHttpRequest to post data, the code typically follows this structure: var xhr = new XMLHttpRequest(); var url = 'http://myurl/post'; xhr.open("POST", url, true); xhr.setRequestHeader("Content-type", " ...

Guide on saving an Express session into a MongoDB database through a controller handling

I'm experiencing a problem with my controller where the session is not being stored properly even after implementing the necessary express session code app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, ...

I am interested in incorporating a captcha system using ajax

Recently, I implemented email and captcha validation in a form. Now, I am looking to make some modifications. Specifically, I want the form to not reload the page if the captcha is incorrect or left empty. This means that all fields that have already bee ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...

Leverage the power of getServerSideProps when working with Dynamic Routes

I have been working on implementing getServerSideProps in my file named [username].js which utilizes dynamic routing. Next.js requires the use of both getStaticPaths() and getStaticProps({ params }) for dynamic routing. However, there seems to be an issu ...

There is a clash between the webpack-dev-server package and its subdependency, the http-proxy-middleware

Awhile back, I integrated webpack-dev-server v3.11.0 into my project, which - upon recent inspection - relies on http-proxy-middleware v0.19.1 as a dependency. Everything was running smoothly until I separately installed the http-proxy-middleware package a ...

Implementing reCaptcha on React Native: A Step-by-Step Guide

Currently, I am in the process of integrating a reCaptcha validator into a login screen for a react-native application that needs to function seamlessly on both web and mobile platforms. Despite being relatively new to programming and lacking experience w ...

Having trouble extracting the Top-Level Domain from a URL

I'm struggling to find a reliable way to extract the Top-Level Domain from a URL. The challenge I'm facing is that the URLs entered by users can vary greatly - they might enter www.google.com, m.google.com, m.google.uk, google.uk, or www.m.google ...

To effectively execute a JQuery / Javascript function, it is essential to incorporate both $(document).ready and $(document).ajaxSucces

I have a JavaScript function that is used for basic UI functionality across my site. Some elements affected by this function are injected via Ajax, while others are static HTML. Currently, I have duplicated the function and applied it to both $(document). ...

Traversing JSON data in a recursive manner without definite knowledge of its size or nesting levels

Currently, I'm working on a chrome app that utilizes local storage. The backend returns JSON data which I then save locally and encrypt all the items within the JSON. I have multiple sets of JSON with different encryption functions for each set. I at ...

Toggle the div if the if statement is true; otherwise, hide the broken

click: function(event, data) { $('#clicked-state') .text('You clicked: '+data.name); if (data.name == "VA") { $('#va').toggle(); } else { $('#va').style.d ...

Next.js page transitions causing Google Tag Manager to malfunction with 'react-gtm-module'

I am currently working on a Next.js project and have successfully integrated Google Tag Manager (GTM) using the react-gtm-module package. Interestingly, everything works perfectly when the application is initially loaded in debug mode, regardless of the st ...

Cypress is having trouble loading a particular URL

I'm encountering a timeout error while trying to load a specific URL using Cypress. Even after setting the page load time to 2 minutes, the issue persists. Interestingly, general URLs like https://www.google.co.nz/ load without any problems. it(' ...

Collapsing Bootstrap menu bar causing logo overlap

When the navbar collapses (when it shows the toggle icon), the menu items (home, services, portfolio, about, contact) overlap with the logo. If I remove the position:absolute from the logo (navbar-brand), the menu appears in the center. Is there a way to h ...

Teaching jQuery selectors to detect recently-added HTML elements

Unable to find a solution in the jQuery documentation, I am seeking help here for my specific issue. Embracing the DRY principle, I aim to utilize JavaScript to include a character countdown helper to any textarea element with maxlength and aria-described ...

Are multiple .then(..) clauses in Javascript promises better than just using one .then(..) clause?

In this particular scenario, I have set up a basic 'toy' node.js server that responds with the following JSON object: { "message" : "hello there" } This response is triggered by making a GET request to "http://localhost:3060/" So, it's reall ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...