3

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" .

5

1 Answer 1

10

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.