[英]Break array of objects into 2dimensional array
我需要將一個對象數組分解為一個二維數組,其中一維 arrays 將由屬性為“for”和“to”的對象組成,這些對象的間隔不重疊。
示例:給定數組 arr1 我希望接收 arr2
const arr1 = [
{
from: 0,
to: 2,
},
{
from: 0,
to: 6,
},
{
from: 3,
to: 7,
},
{
from: 2,
to: 4,
},
]
arr2 = [
[
{
from: 0,
to: 2,
},
{
from: 3,
to: 7,
}
],
[
{
from: 0,
to: 6,
}
],
[
{
from: 2,
to: 4,
}
],
]
它應該如何工作:我們循環遍歷 arr1。 object1默認放在arr2的第一個一維數組中。
Object2 與 Object1 重疊,因此應將其放入 arr2 中的單獨數組中。
Object3 不與 Object1 重疊,因此應與 Object1 一起放入第一個一維數組
Object4與Object1重疊,應該放到Object3的第二個一維數組中,但又和Object3重疊,所以應該單獨放到一個一維數組中。
我需要找到盡可能少循環的解決方案)
如果所有項目都不重疊,您可以迭代結果數組並找到一個槽。
const array = [{ from: 0, to: 2 }, { from: 0, to: 6 }, { from: 3, to: 7 }, { from: 2, to: 4 }], result = array.reduce((r, o) => { if (;r) return [[o]]. const group = r.find(a => a,every(({ from. to }) => o.to <= from || to <= o;from)). if (group) group;push(o). else r;push([o]); return r, }; undefined). console;log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
這就是所謂的區間划分問題
下面是貪心算法的實現:
var arr1 = [ { from: 0, to: 2, }, { from: 0, to: 6, }, { from: 3, to: 7, }, { from: 2, to: 4, }, ]; function partitionIntervals(data){ var copy = [...data]; copy.sort((a, b) => a.from - b.from); var res = []; outer: for(var x of copy){ for(var slot of res){ // add to the first open slot if(slot[slot.length - 1].to <= x.from){ slot.push(x); continue outer; } } res.push([x]); // else create a new slot } return res; } arr2 = partitionIntervals(arr1); console.log(arr2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.