簡體   English   中英

javascript數組由兩個鍵混合

[英]javascript array mix by two keys

我有以下 3 個(或更多)不同類型和組的數組:讓我們說顏色和形狀,我想盡可能多地傳播該項目(不是隨機的)

['blue', 'green', 'red']
['circle', 'rect', 'tri']

它們被組織在一個數組中

[
  {type: 'blue', group: 'circle'}, {type: 'blue', group: 'rect'}, {type: 'blue',group: 'tri'},
  {type: 'green', group: 'circle'}, {type: 'green', group: 'rect'},
  {type: 'red', group: 'circle'}, {type: 'red', group: 'rect'}, {type: 'red',group: 'tri'},
]

我正在嘗試以兩種不同的組或類型不會相互跟隨並且該組也將跟隨的方式對其進行排序(circle,rect,tri):

[
  {type: 'blue', group: 'circle'}, {type: 'green', group: 'rect'}, {type: 'red',group: 'tri'},
  {type: 'green', group: 'circle'}, {type: 'red', group: 'rect'}, {type: 'blue',group: 'tri'},
  {type: 'red', group: 'circle'}, {type: 'blue', group: 'rect'},
]

我想用幾種不同的方式,先映射組然后類型,映射類型然后組。

這個想法是能夠在屏幕上顯示它(反應),因為不會有兩個類型/組一個挨着另一個。

在需要排序( shapes )的數組上使用forEach循環並計算colors的索引。

 const shapes = ["circle", "rect", "tri"]; const colors = ["blue", "green", "red"]; const res = []; colors.forEach((_, ci) => { shapes.forEach((group, si) => { const type = colors[(ci + si) % colors.length]; res.push({ type, group }); }); }); console.log(res);

我有一個工作代碼,結果是可預測的,而不是隨機的:

let types = ['blue', 'green', 'red', 'black'];
let groups = ['circle', 'rect', 'tri'];

let result = [], index1 = 0; index2 = 0;
let totalResult = types.length * groups.length;
for (let i = 0; i < totalResult; i++) {
    result.push({type: types[index1], group: groups[index2]});
    index1++;
    index2++;

    // Reset counter
    if (index1 === types.length) index1 = 0;
    if (index2 === groups.length) index2 = 0;
}

console.log(result)

並且輸出滿足您的要求。 你可以試試嗎?

您可以通過生成所有可能的對來采用蠻力方法,然后通過使用回溯算法避免重復來收集對。

 function getAllPairs(left, right) { var pairs = []; for (let i = 0; i < left.length; i++) { for (let j = 0; j < right.length; j++) { pairs.push([left[i], right[j]]); } } return pairs; } function check(array) { const sets = [new Set, new Set]; return array.every(a => a.every((v, i) => !sets[i].has(v) && sets[i].add(v))); } function fill(result, pairs) { if (!pairs.length) return result; var left = result.slice(Math.floor(result.length / half) * half); for (let i = 0; i < pairs.length; i++) { if (check([...left, pairs[i]])) { var newResult = fill([...result, pairs[i]], [...pairs.slice(0, i), ...pairs.slice(i + 1)]); if (newResult) return newResult; } } } var type = ['blue', 'green', 'red'], group = ['circle', 'rect', 'tri'], half = Math.sqrt(type.length * group.length), result = fill([], getAllPairs(type, group)) .map(([type, group]) => ({ type, group })); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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