user1334589
user1334589

Reputation: 125

Filter two arrays

I have the following set of arrays,

var records = [{ 'id': 'ee31ee6a-7f95-49fb-a02f-2a9ef36c2f8b', 
'name': 'Test', 'type': 'user' },
{ 'id': 'ee31ee6a-7f95-49fb-a02f-2a9ef36c2f8b', 
'name': '9300731e-3c97-4719-8dc2-fcf0a29fd770', 'type': 'register' },
{ 'id': 'ee31ee6a-7f95-49fb-a02f-2a9ef36c2f8b', 
'name': '9300731e-3c97-4719-8dc2-fcf0a29fd772', 'type': 'register' },
];

var registration = [
{ 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd770', 'id': '123', 'index': '9300731e-3c97-4719-8dc2-fcf0a29fd770'}, 
{ 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd772', 'id': '456', 'index': '9300731e-3c97-4719-8dc2-fcf0a29fd770'}, 
{ 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd771', 'id': '789' 'index': '9300731e-3c97-4719-8dc2-fcf0a29fd776'}];

and want the following output

result = [
{ 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd770', 'id': '123'}, 
{ 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd772', 'id': '456'}]

I basically want the registration array filtered based on the name property in the records arrays as I need the id values from the registration array.

Is there a combination of methods from the lodash library that I could use to get the desired output?

Upvotes: 1

Views: 697

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386868

You could use _.intersectionBy.

var records = [{ 'id': 'ee31ee6a-7f95-49fb-a02f-2a9ef36c2f8b', 'name': 'Test', 'type': 'user' }, { 'id': 'ee31ee6a-7f95-49fb-a02f-2a9ef36c2f8b', 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd770', 'type': 'register' }, { 'id': 'ee31ee6a-7f95-49fb-a02f-2a9ef36c2f8b', 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd772', 'type': 'register' }],
    registration = [{ 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd770', 'id': '123', 'index': '9300731e-3c97-4719-8dc2-fcf0a29fd770'}, { 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd772', 'id': '456', 'index': '9300731e-3c97-4719-8dc2-fcf0a29fd770'}, { 'name': '9300731e-3c97-4719-8dc2-fcf0a29fd771', 'id': '789', 'index': '9300731e-3c97-4719-8dc2-fcf0a29fd776'}],
    result = _.intersectionBy(registration, records, "name");

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

Upvotes: 1

georg
georg

Reputation: 215049

Something like this should work

result = _.filter(registration, x => _.some(records, {name: x.name}))

Upvotes: 0

Related Questions