0

Here is an array of JSON objects that has array values that I want to group by (pull unique):

let myArray = [
    {
        "_id": "1",
        "subdata": [
            {
                "subid": "11",
                "name": "A"
            },
            {
                "subid": "12",
                "name": "B"
            }
        ]
    },
    {
        "_id": "2",
        "subdata": [
            {
                "subid": "12",
                "name": "B"
            },
            {
                "subid": "33",
                "name": "E"
            }
        ]
    }
]

Finally I need to get:

[
    {
        "subid": "11",
        "name": "A"
    },
    {
        "subid": "12",
        "name": "B"
    },
    {
        "subid": "33",
        "name": "E"
    }
]

I've tried lodash with no success:

let newArray = lodash.uniqBy(lodash.concat(myArray, 'subdata.subid'), '_id');

Of course I can scan each array element one by one but thought there is easy way to do it with lodash

1 Answer 1

1

Use _.flatMap() to get the an array of all subdata items, and then use _.uniqueBy() with subid:

const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];

const result = _.uniqBy(_.flatMap(myArray, 'subdata'), 'subid');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

With lodash/fp you can generate a function using _.flow() with the same methods:

const fn = _.flow(
  _.flatMap('subdata'),
  _.uniqBy('subid')
);

const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];

const result = fn(myArray);

console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.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.