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