Search code examples
javascriptlodash

Javascript: Matching Objects in Multiple Arrays of Objects + Aliases


I want to match multiple arrays and build another array whenever there is match. The key could match in any number of arrays or none at all.

[ [{ 'a': 13 }, { 'b': 62 }, { 'c': 93 }, { 'd': 52 }],
  [{ 's': 15 }, { 'y': 15 }, { 'x': 78 }, { 'd': 84 }],
  [{ 't': 35 }, { 'd': 33 }, { 'x': 12 }, { 'c': 62 }] ]

Desired result:

[ {label: c,  arr1: 93,    arr2: null,  arr3: 63},
  {label: d,  arr1: 52,    arr2: 84,    arr3: 33},
  {label: x,  arr1: null,  arr2: 78,    arr3: 12} ]

.

label   arr1    arr2    arr3
============================
c       93      null    62
d       52      84      33
x       null    78      12

A more advanced question to go along with that. Is it possible to alias some keys. Eg. perhaps 'b' is also known as 'y', and 's' as 't'.


Solution

  • Try something like this:

    let output = [];
    let aliases = {'b': ['y'], 's': ['t']};
    let totalArrays = yourArray.length;
    
    yourArray.forEach((innerArray, i) => 
       innerArray.forEach(obj =>{
          for(var key in obj){
             let current = output.find(e => e.label == key || (aliases[e.label] || []).indexOf(key) !== -1);
                if(!current){
                   current = { label: key };
                   for(let i = 0; i < totalArrays; i++){
                       current['arr' + (i + 1)] = null;
                   }
                   output.push(current);
               }
    
               current['arr'+ (i +1)] = obj[key];
           } 
     }));