简体   繁体   English

Javascript - 处理多维数组

[英]Javascript -Processing Multidimensional array

Arrayinarray=[];
let options = driver.findElements(By.css("[section='trim'] select"));
options.then(swap=>{
    swap.map((key)=>{
        var s=key.findElements(By.css("option"));
        s.then(mt=>{
            Arrayinarray.push(mt)
        })
    })

});

this is my selenium code.这是我的硒代码。

I have to get each element of the array in correct order我必须以正确的顺序获取数组的每个元素

For example.例如。

var Arrayinarray=[[1,2,3],[4,5,6,5],[7,8,9],[1,6,3],[1,5,7][1,2,2],[7,2,9,3]];

Expected output:预期输出:

1471117 1471112 1471119 1471113 1471127 1471122
1471129 1471123 1471127 1471122 1471129 1471123
...

I have to permutate the combination of this multidimensional array.我必须排列这个多维数组的组合。 I placed many for loops and map functions.我放置了许多for循环和map函数。 However, it does not work.但是,它不起作用。

You could take a iterative approach by collecting all part arrays and take the final arrays for getting a number back.您可以通过收集所有部分数组并采用最终数组来获取数字来采用迭代方法。

 var values = [[1, 2, 3], [4, 5, 6, 5], [7, 8, 9], [1, 6, 3], [1, 5, 7], [1, 2, 2], [7, 2, 9, 3]], result = values .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), [])) .map(s => +s.join('')); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

The number of results can quickly grow large.结果的数量会迅速增加。 In your case it will have 3*4*3*3*3*3*4 results, ie 3888 results, but making some of the sub arrays larger, and/or adding more of them multiplies the number of results quickly.在您的情况下,它将有 3*4*3*3*3*3*4 结果,即 3888 个结果,但是使一些子数组更大,和/或添加更多子数组会快速增加结果数。

You could use a generator function and then select the first X results from it, or all of them (which I do below):您可以使用生成器函数,然后从中选择第一个 X 结果,或所有结果(我在下面这样做):

 function * generateCombis(arr) { if (arr.length === 1) return yield * arr[0]; const shift = 10**(arr.length-1); for (let val of arr[0]) { for (let val2 of generateCombis(arr.slice(1))) yield val*shift+val2 } } // Example var Arrayinarray=[[1,2,3],[4,5,6,5],[7,8,9],[1,6,3],[1,5,7], [1,2,2],[7,2,9,3]]; const result = Array.from(generateCombis(Arrayinarray)); console.log(result);

Using the spread syntax, you could make the function take the subarrays as separate arguments (instead of taking a nested array), which makes some parts of the code more readable (but that is debatable):使用扩展语法,您可以使函数将子数组作为单独的参数(而不是嵌套数组),这使代码的某些部分更具可读性(但这是有争议的):

 function * generateCombis(current, ...rest) { if (!rest.length) return yield * current; const shift = 10**rest.length; for (let val of current) { for (let val2 of generateCombis(...rest)) yield val*shift+val2 } } // Example var Arrayinarray=[[1,2,3],[4,5,6,5],[7,8,9],[1,6,3],[1,5,7], [1,2,2],[7,2,9,3]]; const result = Array.from(generateCombis(...Arrayinarray)); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM