简体   繁体   English

Java中带有1D数组的锯齿状多维数组的明智筛选

[英]Element-Wise Filtering of Jagged Multidimensional Array with 1D array in Javascript

 const Amaths = [ [1, 2, 3, 5, 6, 7, 8], [4, 5, 6, 8], [12, 3, 4] ] const checks = [2.5, 4.01, 5]; const picks = []; for (let j = 0; j < Amaths.length; j++) { for (let k = 0; k < Amaths[j].length; k++) { if (Amaths[j][k] > checks[j]) { picks.push(Amaths[j][k]); } } } console.log("picks", picks) 

I want to filter a jagged multidimensional array element-wis without flattening the output array; 我想过滤锯齿状的多维数组元素而不会展平输出数组; in this example, "picks". 在此示例中,为“点”。

I have tried using a for loop but the output, "picks", is flattened. 我已经尝试过使用for循环,但是输出“点”却变平了。 Also, I have used mathjs library function, but it seems the element-wise arithmetic operations in this library only works for non-jagged multidimensional arrays. 另外,我已经使用了mathjs库函数,但是似乎该库中的逐元素算术运算仅适用于无锯齿的多维数组。

The expected result should be: 预期结果应为:

 const picks = [ [3, 5, 6, 7, 8], [5, 6, 8], [12] ] console.log ("expected picks", picks) 

Use .map to transform into another 2d array, calling .filter on each subarray while comparing against the checks at the index of the subarray being iterated over: 使用.map转换为另一个2d数组,在每个子数组上调用.filter ,同时与要迭代的子数组索引处的checks进行比较:

 const Amaths = [ [1, 2, 3, 5, 6, 7, 8], [4, 5, 6, 8], [12, 3, 4] ] const checks = [2.5, 4.01, 5]; const result = Amaths.map( (subarr, i) => subarr.filter( num => num >= checks[i] ) ); console.log(result); 

To fix your original code, you'd have to push a new subarray to picks on every outer iteration: 要修复原始代码,您必须在每个外部迭代中推送一个新的子数组以进行picks

 const Amaths = [ [1, 2, 3, 5, 6, 7, 8], [4, 5, 6, 8], [12, 3, 4] ] const checks = [2.5, 4.01, 5]; const picks = []; for (let j = 0; j < Amaths.length; j++) { picks.push([]); for (let k = 0; k < Amaths[j].length; k++) { if (Amaths[j][k] > checks[j]) { picks[j].push(Amaths[j][k]); } } } console.log("picks", picks) 

(but array methods are probably a much better choice here, they're a lot more concise and easy to understand) (但是数组方法可能是一个更好的选择,它们更加简洁易懂)

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

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