簡體   English   中英

遍歷Map中的每對元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM