为什么这个二维数组过滤不起作用?

Why is this 2D array filtering not working?

我有这个二维数组,我正在尝试过滤它,但它未经过滤就出来了:

数据:

[
 ["Val #","Val #","Val #","Val #","Val #"],
 ["SO-000379-001A-047-1","SO-000379-001A-047-2","-","-","-"]
]

筛选行:

cads = cads.filter(e => e[1] != "-" || e[1] != '');

预期结果:

[
 ["Val #","Val #"],
 ["SO-000379-001A-047-1","SO-000379-001A-047-2"]
]

WTHeck 我是不是不见了?

谢谢!

应该是

const data = [
 ["Val #","Val #","Val #","Val #","Val #"],
 ["SO-000379-001A-047-1","SO-000379-001A-047-2","-","-","-"]
]

const result = data.map(d => d.filter(v => !['', '-'].includes(v)))

console.log(result)

您想过滤掉内部数组而不是主要数组

所以你必须映射每个外部数组,然后过滤单行

这是你需要的吗?根据 x 轴和 y 轴过滤项目。

const cads = [
  ["Val #", "Val #", "Val #3", "Val #", "Val #"],
  ["SO-000379-001A-047-1", "-", "SO-000379-001A-047-2", "-", "-"]
]

function f(data) {
  if (!(data && data.length)) {
    return []
  }
  const v = []
  const m = data.length;
  const n = data[0].length;
  const check = (x) => x !== '-' && x !== ''
  for (let i = 0; i < n; i++) {
    let f = true
    for (let j = 0; j < m; j++) {
      if (!check(data[j][i])) {
        f = false
        break;
      }
    }
    if (f) {
      for (let k = 0; k < m; k++) {
        v[k] = v[k] || []
        v[k].push(data[k][i]);
      }
    }
  }
  return v
}
console.log(f(cads))

let data = [
 ["Val #","Val #","Val #","Val #","Val #"],
 ["SO-000379-001A-047-1","SO-000379-001A-047-2","-","-","-"]
]

for (let i = 0; i <= data[1].length; i++) {
    if(data[1][i] === "-"){
        data[0].splice(i,1);
        data[1].splice(i,1);
        i--;
    }
}

console.log(data);

不够聪明,无法使用那些 Array.map/filter 函数,但我想这就是您想要的?

描述

我相信您正在寻找的是一种根据第二行中的项目过滤数组的两行的方法。这是一个如何做到这一点的例子。我稍微更改了您的数据以显示它正在过滤第 1 行。

脚本

function test() {
  try {
    let data = [ ["Val 1","Val 2","Val 3","Val 4","Val 5"],
                  ["SO-000379-001A-047-1","","SO-000379-001A-047-2","-","-"] ];
    let result = [[],[]];
    data[1].forEach( (item,i) => {
      if( (item != "-") && (item != "") ) {
        result[0].push(data[0][i]);
        result[1].push(data[1][i]);
      }
    });
    console.log(result);
  }
  catch(err) {
    console.log(err);
  }
}

Console.log

8:23:57 AM  Notice  Execution started
8:23:58 AM  Info    [ [ 'Val 1', 'Val 3' ],
  [ 'SO-000379-001A-047-1', 'SO-000379-001A-047-2' ] ]
8:23:57 AM  Notice  Execution completed

从问题中看不出你想要达到什么目的。以下脚本是自最新 ECMA 以来过滤此类嵌套数组的最简单方法。我这里使用的条件是过滤掉只包含"-"的字符串,但是你可以修改为add/remove其他条件

let array = [
     ["Val #","Val #","Val #","Val #","Val #"],
     ["SO-000379-001A-047-1","SO-000379-001A-047-2","-","-","-"]
     ]
let filtered = [];
for (e of array) {
  let kept = [];
  for (item of e) {
    if (item != "-") kept.push(item);
  }
  filtered.push(kept);
}
console.log(filtered);