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

How do I collapse an array of arrays into an array of all the elements?

本文关键字:数组 元素 折叠      更新时间:2023-09-26

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

, 2, null ], [ 9 ], [ 2, null, null ] ]我

想要一个简单的函数来返回我 [ 1, 2, 9, 2 ],如您所见,消除了 null。

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

谢谢!

始终深一层

var arr  = [ [ null, 1, 2, null ], [ 9 ], [ 2, null, null ] ],
    arr2 = [];
arr2 = (arr2.concat.apply(arr2, arr)).filter(Boolean);

小提琴

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

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]

喜欢这个?

您可以使用 LoDash 库来实现这一点。

_.flatten()

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

_.compact()

创建一个删除所有假值的数组。值为假, null、0、"、undefined 和 NaN 都是假的。

这是示例

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

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