Reputation: 2929
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.
Upvotes: 2
Views: 91
Reputation: 30088
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>
Upvotes: 3