0

I have array like this:

[
  [
    {id:1, name:'xxx'}
  ],
  [
    {id:2, name:'xxx'},
    {id:1, name:'xxx'}
  ],
  [
    {id:2, name:'xxx'},
    {id:1, name:'xxx'},
    {id:3, name:'xxx'}
  ]
]

I need pick just objects with unique id and merge them into one array. Each object has id property, so I tried this:

_.(data).union().uniqBy(o => o.id).value()

but it gives me wrong result.

My required output should be like this:

[{id:1, name:'xxx'}, {id:2, name:'xxx'}, {id:3, name:'xxx'}]

Can you help me with that? Thanks.

6
  • 2
    Post a real example (input data) and the expected result. Commented Mar 20, 2018 at 17:48
  • 2
    Would _.uniqBy(_.flattenDeep(data), "id") do what you're wanting? Commented Mar 20, 2018 at 17:49
  • @CRice: Seems right to me. Commented Mar 20, 2018 at 17:53
  • @Ele I edited question, check it please. Commented Mar 20, 2018 at 17:54
  • @CRice I'll try it and give you response Commented Mar 20, 2018 at 17:55

1 Answer 1

1

Use _.flatten() to merge the sub arrays into a single array and then apply _.uniqBy():

const data = [[{"id":1,"name":"xxx"}],[{"id":2,"name":"xxx"},{"id":1,"name":"xxx"}],[{"id":2,"name":"xxx"},{"id":1,"name":"xxx"},{"id":3,"name":"xxx"}]];

const result = _(data)
  .flatten()
  .uniqBy('id')
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/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.