如何删除所有空值的数组列?

时间:2014-12-08 15:41:32

标签: javascript arrays

说我有这个数组,

[
  ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh"],
  ["A"    , 1       , 2      , 3       , 4      , 5      , null     ],
  ["B"    , 1       , 2      , null    , null   , 5      , null     ],
  ["C"    , null    , 2.5    , 3       , 4      , 5      , null     ],      
]

现在,它是字符串,整数,浮点数/双精度数和空值的混合。在最后一列中,每个值都为null,我需要删除该列(忽略第一行不为空的事实)。

我认为这样做的唯一方法是遍历整个数组(和子数组),并为每个列保留一个布尔值,说明所有值是否为null,然后再次循环遍历它,如果列完全为null,则删除索引。

这对我来说似乎效率很低,我想知道是否有更好的方法可以做到这一点。

只是你有一个想法,输出数组,需要像这样。

[
  ["First", "Second", "Third", "Fourth", "Fifth", "Sixth"],
  ["A"    , 1       , 2      , 3       , 4      , 5      ],
  ["B"    , 1       , 2      , null    , null   , 5      ],
  ["C"    , null    , 2.5    , 3       , 4      , 5      ],      
]

// The "Seventh" column was removed due to all it's values being null.

我将设置一个jsfiddle示例,我将在完成后编辑链接。

Here's my rough proof of concept了解我的循环理念。

1 个答案:

答案 0 :(得分:2)

这样的事情可以解决问题

function remove(arr) {
   var toRemove = Array.apply(null, new Array(arr[0].length)).map(function(_, i){return i;});

   arr.slice(1).forEach(function(row){
      toRemove = toRemove.filter(function(index){//filter only values that left
         return row[index] === null;
      });
   });

  return arr.map(function(row){
      return row.filter(function(_, i){
        return toRemove.indexOf(i) < 0;
     });
  });
}