Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine nested arrays into one?

Let's say I have an array of objects that look similar to this:

[
   {
     id: ...,
     name: "...",
     users: [1, 2, 3]
    },
    ...
]

Is there a way that I can easily merge the .users array of each object into one array?

like image 937
m0ngr31 Avatar asked Apr 29 '15 21:04

m0ngr31


People also ask

How do I combine multiple arrays into one?

Using the spread operator or the concat() method is the most optimal solution. If you are sure that all inputs to merge are arrays, use spread operator . In case you are unsure, use the concat() method. You can use the push() method to merge arrays when you want to change one of the input arrays to merge.

How do I flatten a nested array?

The array method accepts an optional parameter depth , which specifies how deep a nested array structure should be flattened (default to 1 ). So to flatten an array of arbitrary depth, just call flat method with Infinity .

How do you combine two arrays into an array of objects?

To combine two arrays into an array of objects, use map() from JavaScript.

How do you combine array elements?

Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.


2 Answers

Pluck 'n' flatten will do what you want:

var result = _.flatten(_.pluck(data, 'users'));

Edit

As Richard points out, pluck was removed from lodash in version 4.0.0 but still remains in the current version of underscore at time of writing (1.8.3).

Replacing pluck with map works for both lodash and underscore:

var result = _.flatten(_.map(data, 'users'));
like image 160
Gruff Bunny Avatar answered Sep 27 '22 21:09

Gruff Bunny


Do not know lodash or underscore, but you can use the native forEach and concat methods of Array (underscore may have equivalent methods, and polyfills for older browsers)

var data = [{
     id: ...,
     name: "...",
     users: [1, 2, 3]
    },
    ...
];
var allUsers = [];
data.forEach(function(obj){
   allUsers = allUsers.concat(obj.users);
});

console.log(allUsers);

Demo

var data = [{
     id: 1,
     name: "...",
     users: [1, 2, 3]
    },
    {
     id: 2,
     name: "....",
     users: [4, 5, 6]
    },
    {
     id: 3,
     name: "...",
     users: [7, 8, 9]
    },            
];
var allUsers = [];
data.forEach(function(obj){
   allUsers = allUsers.concat(obj.users);
});

document.querySelector("#log").innerHTML = allUsers.join(",");
<div id="log"></div>
like image 36
Patrick Evans Avatar answered Sep 27 '22 21:09

Patrick Evans