admin管理员组

文章数量:1356709

I have an array of the form: [ [ null, 1, 2, null ], [ 9 ], [ 2, null, null ] ]

And I would like a simple function to return me [ 1, 2, 9, 2 ] where, as you can see, eliminates the null.

I need this because some values in the database are returned in this form, and I would then make a query with the example returned but without the nulls.

Thanks!

I have an array of the form: [ [ null, 1, 2, null ], [ 9 ], [ 2, null, null ] ]

And I would like a simple function to return me [ 1, 2, 9, 2 ] where, as you can see, eliminates the null.

I need this because some values in the database are returned in this form, and I would then make a query with the example returned but without the nulls.

Thanks!

Share Improve this question asked Oct 4, 2013 at 22:01 DiscipolDiscipol 3,1574 gold badges24 silver badges43 bronze badges 2
  • 1 So you want to pletely flatten the array and remove the null? Is the array always one level deep? – jamesplease Commented Oct 4, 2013 at 22:03
  • Yes and yes, always one level deep. – Discipol Commented Oct 4, 2013 at 22:05
Add a ment  | 

3 Answers 3

Reset to default 6

always one level deep

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

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

FIDDLE

Assuming a possible nested array structure:

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]

like this?

You can use LoDash library to achieve this.

_.flatten()

Flattens a nested array (the nesting can be to any depth).

_.pact()

Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are all falsey.

Here is Example

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

Output: [1, 2, 9, 2]

本文标签: javascriptHow do I collapse an array of arrays into an array of all the elementsStack Overflow