To start, create an index by linking each unique identifier to its respective object. The structure of the index object should resemble this:
{
'11': { id: 11, name: 'name 1' },
'12': { id: 12, name: 'name 2' },
'13': { id: 13, name: 'name 3' },
'14': { id: 14, name: 'name 4' }
}
There are various methods to construct this index, one option being using Object.fromEntries
. Employ
Object.fromEntries(arr2.map(obj => [obj.id, obj]))
.
Next, associate each id
from your arr1
with its corresponding object through a lookup in the established index
object: index[id]
. This process can be achieved with arr1.map(id => index[id])
.
var arr1 = [11, 12, 13];
var arr2 = [
{ id: 11, name: "name 1" },
{ id: 12, name: "name 2" },
{ id: 13, name: "name 3" },
{ id: 14, name: "name 4" },
];
const index = Object.fromEntries(arr2.map(obj => [obj.id, obj]));
const result = arr1.map(id => index[id]);
console.log(result);
This strategy excels in efficiency as it avoids conducting a linear search for every item's index (rendering no need for .includes
or .find
per entry). Instead, it capitalizes on the swift hashtable retrieval of a property within an object (maintaining more or less constant time complexity). Overall, the operation is O(N) rather than O(N^2).
Nonetheless, be cautious as there may be elevated overheads when generating such an index with small N values. Yet, for larger N values, this method will prove superior and particularly useful if there are multiple variations of arr1
objects to be paired with a single arr2
.