[英]Iterating over every pair of elements in a Map
我有一个Map,其中保存Shape对象的值及其ID为键。 我需要遍历此Map中的每对Shape,但是我只想遍历每对一次。
我知道我可以使用forEach或for..of,但是我找不到防止重复对的方法。 同样,这应该是尽可能高效的。
shapes.forEach((shape1, shapeId1) => {
shapes.forEach((shape2, shapeId2) => {
// iterating over each pair many times
});
});
我建议先将Map
转换为其条目的数组:
const entryArray = Array.from(shapes.entries());
然后,您可以选择通过传统的for
循环迭代对:
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);
}
}
或通过功能性的forEach
数组方法:
console.log("FOREACH");
entryArray.forEach(([shapeId1, shape1], i) =>
entryArray.slice(i + 1).forEach(([shapeId2, shape2]) => {
console.log(shapeId1, shapeId2);
})
);
在每种情况下,通过内部循环避免仅在外部循环索引之后对元素进行迭代即可避免重复。 我不知道您的Shape
或id类型是什么样,但是鉴于此:
interface Shape {
area: number;
}
const shapes: Map<string, Shape> = new Map([
["a", { area: 1 }],
["b", { area: 2 }],
["c", { area: 3 }]
]);
上面的代码输出
FOR LOOP
a b
a c
b c
FOREACH
a b
a c
b c
因此,您可以看到得到不同的对。 希望能有所帮助; 祝好运!
将Set与两个索引一起使用:
let indexes = new Set();
shapes.forEach((shape1, shapeId1) => {
shapes.forEach((shape2, shapeId2) => {
if (set.has(`${shapeId1}-${shapeId2}`) || set.has(`${shapeId2}-${shapeId1}`)) return;
set.add(`${shapeId1}-${shapeId2}`);
});
});
您可以使用索引使用两个进行迭代,并从根索引+ 1开始嵌套迭代。这将确保您永远不会处理两对。
const arr = [1,2,3,4];
for (let i = 0; i<arr.length-1; i++) {
for (let j = i+1; j<arr.length; j++) {
console.log(`${arr[i]} - ${arr[j]}`)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.