如何将数组数组折叠为所有元素的数组?

时间:2013-10-04 22:01:32

标签: javascript

我有一个形式的数组:[[null,1,2,null],[9],[2,null,null]]

我想要一个简单的函数来返回[1,2,9,2],正如你所看到的那样,消除了null。

我需要这个,因为数据库中的某些值是以这种形式返回的,然后我会使用返回的示例进行查询但没有空值。

谢谢!

3 个答案:

答案 0 :(得分:4)

  总是一层深的

var arr  = [ [ null, 1, 2, null ], [ 9 ], [ 2, null, null ] ],
    arr2 = [];

arr2 = (arr2.concat.apply(arr2, arr)).filter(Boolean);

FIDDLE

答案 1 :(得分:4)

假设一个可能的嵌套数组结构:

var reduce = function(thing) {

  var reduction = [];

  // will be called for each array like thing
  var loop = function(val) {

    // an array? 
    if (val && typeof val === 'object' && val.length) {
      // recurse that shi•
      reduction = reduction.concat(reduce(val));
      return;
    }

    if (val !== null) {
       reduction.push(val);
    }

  };

  thing.forEach(loop);

  return reduction;
};

reduce([ [ null, 1, 2, null ], [ 9 ], [ 2, null, null ] ]); 
// [1, 2, 9, 2]

reduce([1, 3, 0, [null, [undefined, "what", {a:'foo'}], 3], 9001]);
// [1, 3, 0, undefined, "what", Object, 3, 9001]
像这样?

答案 2 :(得分:1)

您可以使用LoDash库来实现此目的。

_.flatten()

  

展平嵌套数组(嵌套可以是任何深度)。

_.compact()

  

创建一个删除了所有falsey值的数组。值假,   null,0,“”,undefined和NaN都是假的。

这是Example

var test = [
    [null, 1, 2, null],
    [9],
    [2, null, null]
];
test = _.flatten(test);
test = _.compact(test);
console.log(test)

输出: [1, 2, 9, 2]

相关问题