There is no function that will do this, as it is a fairly specialized operation. However, its rather simple composition of underlining functions:
_.values(_.extend(_.indexBy(array1, 'field'), _.indexBy(array2, 'field')))
We use indexBy
to turn arrays into objects bound to the field
value, and then extend
does what we want. Finally, values
returns it back to the array.
Note that while this does not guarantee any guarantees regarding order, in the current _
and v8 implementations, the final array will be things from array1
, followed by things from array2
that are not in array1
, sorted in the original order of each array.
Also note that the _.extend
function is destructive in the first argument, while this does not change any array.
If you want to be sure that the order matches the original array1
:
order = _.object(_.map(array1, function(obj, i) { return [obj.field, i]; })) _.sortBy(_.values(_.extend(_.indexBy(array1, 'field'), _.indexBy(array2, 'field'))), function(obj) { order[obj.field]; })
Here we create a position search table, and then sort the original solution based on the search table.
source share