SQL-style join on arrays using ECMA6 I have a code snippet which performs an SQL-style join on objects in two arrays based on a specific field (in the code below, .id).



let preprocessed_array = [
  {id: 1,category:'a'},
  {id: 2,category:'b'},
  {id: 3,category:'b'}
] 

let new_array = [
  {id: 4},
  {id: 1,category:'b'},
  {id: 5}
] 

 for(let i=0;i&lt; preprocessed_array.length;i++)
 {
   for(let j=0;j&lt;new_array.length;j++)
   {
     if( preprocessed_array[i].id===new_array[j].id)
     {
       new_array[j]=preprocessed_array[i]
     }
   }
 }

 console.log(new_array)




Although this snippet is straightforward, I don't like the imperative style.  Is there a more declarative way to do this just with javascript / ECMA6 arrays?
Build an index and use it to map the second array:

const index = new Map(source.map(el =&gt; [el.id, el]));
const result = picks.map(el =&gt; (index.get(el.id) || el));


The larger the arrays, the more effective the index becomes.
If this code is a bottleneck, it can be rewritten to build the index on-the-go (memoization).

P.S. source stands for preprocessed_array and picks for new_array in the original code.