Join nested array

236 views Asked by At

I have a result from Q.all() which is something like this -

promise = [Arr1,Arr2,Arr3....]

Each Arr can be either null or an array of plain JS objects.

I want to join all these arrays to one big array;

I can loop over and use array concat method to join them.

Is there any other elegant solution which is inbuilt in JS ?

Here is sample array -

    [
      {
        "endDate": "2015-06-11 14:52:00",
        "quantity": 75,
      },
      {
        "endDate": "2015-06-11 14:42:00",
        "quantity": 78,
      },
      {
        "endDate": "2015-06-01 14:43:00",
        "quantity": 69,
      },
      {
        "endDate": "2015-05-14 13:38:00",
        "quantity": 85,
      }
    ]

I have these libraries available as well lodash, angular

2

There are 2 answers

3
T.J. Crowder On BEST ANSWER

I believe that would be a combination of flattenDeep (to do the flattening) and without (to remove nulls — at least, I think you wanted to remove nulls; if not, take without out):

var result = _.without(_.flattenDeep(yourArray), null);

Live Example:

// NOTE: You said you had an array with arrays in it, so I've taken
// the one array you gave and used it as two entries in the array
// below (with some minor mods). Note also the nulls.
var yourArrays = [
    [
        {
            "endDate": "2015-06-11 14:52:00",
            "quantity": 75
        },
        {
            "endDate": "2015-06-11 14:42:00",
            "quantity": 78
        },
        {
            "endDate": "2015-06-01 14:43:00",
            "quantity": 69
        },
        {
            "endDate": "2015-05-14 13:38:00",
            "quantity": 85
        }
    ],
    null,
    null,
    [
        {
            "endDate": "2015-07-11 14:52:00",
            "quantity": 12
        },
        {
            "endDate": "2015-07-11 17:42:00",
            "quantity": 34
        },
        {
            "endDate": "2015-07-01 13:43:00",
            "quantity": 56
        },
        {
            "endDate": "2015-08-14 12:38:00",
            "quantity": 85
        }
    ]
];
var result = _.without(_.flattenDeep(yourArrays), null);
document.body.insertAdjacentHTML(
"beforeend",
"<pre>" + JSON.stringify(result, null, 2) + "</pre>"
);
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>

0
ozil On

you cam simple use .map function.

var promise = [[0,1],[2,3],[],[6,7]]
var combineArr = promise.map(function(value, index, array) {
    return array[index];
  });
alert(combineArr);  

DEMO