2

I have an array, to simplify lets say persons with first, last, and age. I want to make a new array of all persons that have the same first name, same last name and same age. For example my starting array:

[
  {id: 1, first: 'fred', last: 'smith', age: 21},
  {id: 2, first: 'fred', last: 'smith', age: 21},
  {id: 3, first: 'tom', last: 'smith', age: 21},
  {id: 4, first: 'fred', last: 'smith', age: 32}
]

I would like to return the duplicates that match first/last/age:

[
  {id: 1, first: 'fred', last: 'smith', age: 21},
  {id: 2, first: 'fred', last: 'smith', age: 21}
]

I'm struggling with _.uniq to figure out how to do this, any help is appreciated.

3
  • 1
    Would .reduce() do what you want? Compare each item with the previous, and if they match, return the later? Commented May 4, 2016 at 15:42
  • What happens if there are 2 freds and 2 toms? What do you expect in return? Commented May 4, 2016 at 15:52
  • @ Felipe Skinner, if there are 2 freds with the same last name and age, they should be included, if there are 2 toms with same last name and age, they should also be included, basically all records that match on all three criteria. Commented May 4, 2016 at 16:00

1 Answer 1

3

You can make use of _.groupBy() to group values, make sure that it is grouped by values that you determine to be the criteria for a duplicate. You can then _.filter() each grouped values by the lengths of the arrays they accumulated and then _.flatten() it to obtain the final array.

var data = [
  {id: 1, first: 'fred', last: 'smith', age: 21},
  {id: 2, first: 'fred', last: 'smith', age: 21},
  {id: 3, first: 'tom', last: 'smith', age: 21},
  {id: 4, first: 'fred', last: 'smith', age: 32}
];

var result = _(data)
  .groupBy(i => _(i).pick('first', 'last', 'age').values().value())
  .filter(i => i.length > 1)
  .flatten()
  .value();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>

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

1 Comment

Thanks for introducing me you the multi-property form of pick.

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.