I have two arrays of objects and need to find the intersection (objects with same id) in each, and return the intersecting object instance with the lowest score.
This is related to Simplest code for array intersection in javascript but with additional needs to evaluate an attribute on the intersecting items.
array1 = [
{id:'aaa',score:5},
{id:'bbb',score:5},
{id:'ccc',score:20},
{id:'xxx',score:1},
{id:'yyy',score:1},
{id:'zzz',score:20},
]
array2 = [
{id:'aaa',score:1},
{id:'bbb',score:1},
{id:'ccc',score:5},
{id:'zzz',score:60},
]
Finding the intersection by object.id is fairly easy:
shared = array1.filter(a => array2.some(b => a.id === b.id));
But that would return the items in array1 that have common items in array2. What I really want to do is return the intersecting objects with the lowest score.
Desired result:
shared = [
{id:'zzz',score:20},
{id:'ccc',score:5},
{id:'aaa',score:1},
{id:'bbb',score:1}
]
Is there a good way to do this in a single function?
I also need to sort the resulting array sorted by score and then id, but I can probably do that afterwards.