Append nested array

I have a result from Q.all()

that looks something like this:

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

      

Each Arr

can be either null

an array of plain JS objects.

I want to combine all of these arrays into one big array;

I can loop through and use the array method concat

to join them.

Is there any other elegant solution built into JS?

Here is an array of samples -

    [
      {
        "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 also have these libraries lodash

,angular

+3


source to share


2 answers


I believe it is a combination of flattenDeep

(for alignment) and without

(for removing null

s - at least I think you meant to remove null

s, 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>
      

Run codeHide result


+3


source


you just use .map

.

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

      



DEMO

0


source







All Articles