merge 2 array into new array after matching their content javascript -
i have 2 arrays, , want new array based upon condition content of these 2 arrays matched
arr1 = [{ package_id: 'aabbccdd', level: 2 }, { package_id: 'xycd21', level: 3 } ] arr2 = [{ package_id: 'aabbccdd', level: 1 }, { package_id: 'zcb21', level: 5 }] mergedarray = [{ package_id: 'aabbccdd', arr1level: 2, arr2level: 1 }, { package_id: 'xycd21', arr1level: 3, arr2level: 0 }, { package_id: 'zcb21', arr1level: 0, arr2level: 5 }]
so if package_id checked in both arrays. , if found in either array, new array pushed 1 element level both array mentioned against package_id.
i not figure out logic that. if can done lodash kindly tell me.
you can solve using loops did here:
var arr1 = [{ package_id: 'aabbccdd', level: 2 }, { package_id: 'xycd21', level: 3 } ]; var arr2 = [{ package_id: 'aabbccdd', level: 1 }, { package_id: 'zcb21', level: 5 } ]; var mergedarr = []; var tempobj = {}; for(var = 0; < arr1.length; i++){ tempobj.package_id = arr1[i].package_id; tempobj.arr1level = arr1[i].level; tempobj.arr2level = 0; for(var k = 0; k < arr2.length; k++){ if(arr1[i].package_id === arr2[k].package_id){ tempobj.arr2level = arr2[k].level; } } mergedarr.push(tempobj); tempobj = {}; } for(i = 0; < arr2.length; i++){ var isnew = true; for(k = 0; k < mergedarr.length; k++){ if(arr2[i].package_id === mergedarr[k].package_id){ isnew = false; } } if(isnew){ tempobj.package_id = arr2[i].package_id; tempobj.arr2level = arr2[i].level; tempobj.arr1level = 0; mergedarr.push(tempobj); tempobj = {}; } } console.log(mergedarr);
Comments
Post a Comment