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

时间:2019-07-10 22:46:20

标签: javascript for-loop multidimensional-array conditional-statements

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)

我想过滤锯齿状的多维数组元素,而不要展平输出数组;在此示例中,为“点”。

我已经尝试过使用for循环,但是输出“点”却变平了。另外,我已经使用了mathjs库函数,但是似乎该库中的逐元素算术运算仅适用于无锯齿的多维数组。

预期结果应该是:

const picks =  [ [3, 5, 6, 7, 8], [5, 6, 8], [12] ]

console.log ("expected picks", picks)

1 个答案:

答案 0 :(得分:2)

使用.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);

要修复原始代码,您必须在每次外部迭代时将一个新的子数组推入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)

(但是数组方法可能是一个更好的选择,它们更加简洁和易于理解)