Merge two arrays using values of nested object in one of the two arrays

A primer on complex array merging

By: Ajdin Imsirovic 24 March 2019

Here’s a primer on merging two complex arrays.

Merge two arrays Image by Unsplash

Let’s say we have two arrays.

The first array has the following structure:

let arr5 = [
  { id: "101", name: "Cars" },
  { id: "102", name: "Buses" },
  { id: "103", name: "Vans" },
  { id: "104", name: "Trucks" },
  { id: "105", name: "Boats" },
]

The second array has the following structure:

let arr6 = [
  { id: "147", name: "Toyota 2000", description: "A nice red car", vehicleGroupIds: ["101","104"] },
  { id: "148", name: "RV", description: "Mobile home", vehicleGroupIds: ["102"] },
  { id: "149", name: "Toyota 2001", description: "A nice blue car", vehicleGroupIds: ["101"] },
  { id: "150", name: "Ford", description: "Blue Ford van", vehicleGroupIds: ["103"] },
  { id: "152", name: "VW", description: "A VW truck", vehicleGroupIds: ["104"] },
  { id: "153", name: "Pearl of the Seas", description: "A fine big yacht", vehicleGroupIds: ["105"] },
]

We wanna merge arrays, so we’ll do this to begin with:

arr6.forEach(memberObj => memberObj.vehicleGroupIds.forEach(vechicleGroupId => {
arr5.forEach(arr5Obj => { if(arr5Obj.id == vechicleGroupId) { console.log(`The arr5obj id ${arr5Obj.id} is the same as vechicleGroupId ${vechicleGroupId}`) } } ) } ) )

Now let’s prepare the mergedArrays array:

let mergedArrays = [];

Now we’ll write a function to combine the two arrays. Here’s the completed code:

   let mergeArrays = () => {
    let arr1 = arr5;
    let arr2 = arr6;

    arr2.forEach(memberObj => memberObj.vehicleGroupIds.forEach(groupId => {
        arr1.forEach(arr1Obj => {
            if (arr1Obj.id == groupId) {
                mergedArrays.push({
                  vehicleGroupIds: arr1Obj.id,
                  vehicleTypeName: arr1Obj.name,
                  matchingId: groupId,
                  vechicleId: memberObj.id,
                  vechicleame: memberObj.name,
                  vehicleDescription: memberObj.description,
                })
            }
        })
    }))
  }

Finally, we can just call the function with:

mergeArrays();

Here’s how the code above works:

  1. To be continued …

Feel free to check out my work here: