Personally, I like to have a dedicated correlate function for this particular scenario.
"use strict";
function correlate(
outer,
inner,
outerKeyOrKeySelector = x => x,
innerKeyOrKeySelector = x => x
) {
const outerValues = [...outer];
const innerValues = [...inner];
const outerToKey = typeof outerKeyOrKeySelector === 'function'
? outerKeyOrKeySelector
: (x => x[outerKeyOrKeySelector]);
const innerToKey = typeof innerKeyOrKeySelector === 'function'
? innerKeyOrKeySelector
: (x => x[innerKeyOrKeySelector]);
const outerKeyed = outerValues.map(value => ({key: outerToKey(value), value});
const innerKeyed = innerValues.map(value => ({key: innerToKey(value), value});
return outerKeyed.reduce((results, {key: oKey, value: oValue}) => [
...results,
...innerKeyed
.filter(({key: iKey}) => oKey === iKey)
.map(({value: iValue}) => [oValue, iValue])
], []);
}
This basically acts like a JOIN and allows you to correlate the elements two arrays, equating elements directly or by the value of a specified property or projection function.
It may seem like overkill, and YMMV, but I find it very useful.
Applied to the problem at hand:
var reArr = correlate(orderArr, myArr).map(([first, second]) => first);
But it handles complex scenarios just as easily
var correlated = correlate(orders, customers, o => o.customer.name, c => c.name);
correlated.forEach(([order, customer]) => {
customer.orders.push(order);
});