简体   繁体   中英

How to merge array of arrays in one array (in JavaScript)?

I have an array of objects in JavaScript. Each object contains property named "myPropArray", which is actually another array. Here is the structure of this array:

let myBaseArray = [
    {
        myPropArray: ["s1", "s2"],
        someOtherProp: "randomString1"
    },
    {
        myPropArray: ["s2", "s3"],
        someOtherProp: "randomString2"
    }
]

What I need is to take all arrays under this property and to merge them all in one array, without duplicates (in JavaScript). Here is my implementation (using lodash):

_.map(myBaseArray , 'myPropArray') 

Which is actually returning the following result:

[
  ["s1", "s2"],
  ["s2", "s3"]
]

But what I want to accomplish is:

["s1", "s2", "s3"]

Also (if possible) I'm trying to avoid for-each loops, since this needs to me optimized as much as possible and I'm wondering if can be done using lodash mappers or other similar function?

There are already some solutions from this stage where I got ( as the solution here ) but I would like to find a solution tho this problem which will be specific for my "array or objects which contains properties of type Array" .

Extract the property's value with Array.map() , flatten by spreading into Array.concat() , and use a Set to get unique values. Spread the Set back to an array:

 const myBaseArray = [ { myPropArray: ["s1", "s2"], someOtherProp: "randomString1" }, { myPropArray: ["s2", "s3"], someOtherProp: "randomString2" } ] const result = [...new Set([].concat(...myBaseArray.map((o) => o.myPropArray)))] console.log(result) 

The lodash way would be to use _.flatMap() , and _.uniq() :

 const myBaseArray = [ { myPropArray: ["s1", "s2"], someOtherProp: "randomString1" }, { myPropArray: ["s2", "s3"], someOtherProp: "randomString2" } ] const result = _.uniq(_.flatMap(myBaseArray, 'myPropArray')) console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM