temp2 - дерево вариантов.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. let testArr = [
  2. ["USA", "Mexico"],
  3. ["Green", "Red", "Blue"],
  4. ["Metall", "Glass", "Plastic"],
  5. ];
  6. function arrayOfTree(arr = []) {
  7. let iter = arr.reduce((a, b) => a * b.length, 1); // 18
  8. let res = Array.from(Array(iter), () => Array(arr.length)); // 18*3
  9. let step = iter;
  10. let i = 0;
  11. for (let k = 0; k < arr.length; k++) {
  12. step = step / arr[k].length; // 9, 3, 1
  13. // console.log("step - ", step);
  14. i = 0;
  15. for (let j = 0; j < iter; j++) {
  16. res[j][k] = arr[k][Math.floor(i++ / step) % arr[k].length];
  17. }
  18. }
  19. return res;
  20. }
  21. console.log(arrayOfTree(testArr));
  22. // не боится пустого массива на входе
  23. //////////////////
  24. //////////////////
  25. //////////////////
  26. //////////////////
  27. //////////////////
  28. //////////////////
  29. var list = [
  30. ["USA", "Mexico"],
  31. ["Green", "Red", "Blue"],
  32. ["Metall", "Glass", "Plastic"],
  33. ];
  34. var tree = [];
  35. list.forEach(function (listArrayValue, listKey) {
  36. let secondListKeyElement = 1;
  37. if (listKey === 0) {
  38. addElementsToSecondBranch(list, tree, secondListKeyElement, listArrayValue);
  39. }
  40. });
  41. function addElementsToSecondBranch(list, tree, secondListKeyElement, listArrayValue) {
  42. listArrayValue.forEach(function (branchKey) {
  43. tree[branchKey] = [];
  44. if (typeof tree[branchKey] !== "undefined" && typeof list[secondListKeyElement] !== "undefined") {
  45. addElementsToSecondBranch(list, tree[branchKey], secondListKeyElement + 1, list[secondListKeyElement]);
  46. }
  47. });
  48. }
  49. console.log(tree);
  50. /////////////
  51. /////////////
  52. /////////////
  53. /////////////
  54. /////////////
  55. /////////////
  56. /////////////
  57. /////////////
  58. let testArr = [
  59. ["USA", "Mexico"],
  60. ["Green", "Red", "Blue"],
  61. ["Metall", "Glass", "Plastic"],
  62. ];
  63. (() => {
  64. const inc = (indexes) => {
  65. let i;
  66. for (i = testArr.length - 1; i >= 0 && testArr[i].length <= (indexes[i] || 0) + 1; i--);
  67. if (i === -1) return NaN;
  68. indexes[i] = (indexes[i] || 0) + 1;
  69. i < testArr.length - 1 && (indexes[i + 1] = 0);
  70. return [...indexes];
  71. };
  72. let indexes = [0, 0, 0],
  73. result = [];
  74. do {
  75. result.push(indexes.map((i, j) => testArr[j][i || 0]));
  76. } while ((indexes = inc(indexes)));
  77. return result;
  78. })();