Search code examples
javascriptarrayslodashjavascript-objects

Lodash or best approach to combining two arrays of objects with matching key


Working with google-map-react heat map. I need to create a new array of objects from two api responses without that key:value used to compare the arrays

let arr1 = [
  {"db_area":"1", "lat":"42.010531", "lng":"-87.670748"},
  {"db_area":"2", "lat":"42.001567", "lng":"-87.695137"},
  {"db_area":"3", "lat":"41.966063", "lng":"-87.656105"}
]

let arr2 = [
  {"comm_area":"1", "weight":"200"},
  {"comm_area":"2", "weight":"125"},
  {"comm_area":"3", "weight":"33"}
]

result = [
  {"lat":"42.010531", "lng":"-87.670748", "weight":"200"},
  {"lat":"42.001567", "lng":"-87.695137", "weight":"125"},
  {"lat":"41.966063", "lng":"-87.656105", "weight":"33"}
]

I tried to loop booth arrays, and it formatted correctly, but it created an array which the total length was the total of both arrays

const mergedandfilterd = [];

const result = mergedandfiltered;

for (var i = 0; i < arr1.length; i++)
{
    for (var j = 0; j < arr2.length; j++)
    {
        if (obj1[i]['db_area'] == arr2[j]['comm_area'])
        {
            mergedandfiltered.push({
                "lat": arr1[i]['lat'],
                "lng": arr1[i]['lng'],
                "weight": arr2[j]['weight']
            });

            console.log(mergedandfiltered);
        }
    }
}

Solution

  • If you first create a Map (weightMap) from the arr2, then you can use Array.map() on the arr1 to generate your desired result:

    let arr1 = [
      {"db_area":"1", "lat":"42.010531", "lng":"-87.670748"},
      {"db_area":"2", "lat":"42.001567", "lng":"-87.695137"},
      {"db_area":"3", "lat":"41.966063", "lng":"-87.656105"}
    ];
    
    let arr2 = [
      {"comm_area":"1", "weight":"200"},
      {"comm_area":"2", "weight":"125"},
      {"comm_area":"3", "weight":"33"}
    ];
    
    let weightMap = new Map(arr2.map(({comm_area, weight}) => [comm_area, weight]));
    
    let res = arr1.map(
      ({db_area, lat, lng}) => ({lat, lng, weight: weightMap.get(db_area)})
    );
    
    console.log(res);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}