Skip to content

Instantly share code, notes, and snippets.

@aurbano
Created July 2, 2015 14:54
Show Gist options
  • Save aurbano/49af4a2fd927b544bf35 to your computer and use it in GitHub Desktop.
Save aurbano/49af4a2fd927b544bf35 to your computer and use it in GitHub Desktop.
Join two normalized arrays using a join table, returning a copy of the first array containing a property with an array of mapped elements of arr2
/**
* Join two normalized arrays using a join table, returning a copy of
* the first array containing a property with an array of mapped
* elements of arr2
*
* @see normalizeArrayId
*
* @param arr1 Normalized array 1
* @param arr2 Normalized array 2
* @param arrJoin Array with the joins
* @param key1 Key of the property in arrJoin that maps to arr1
* @param key2 Key of the property in arrJoin that maps to arr2
* @param newProperty New property on the returned array that will contain mapped values from arr2
* @return {Array}
*/
function joinArrays(arr1, arr2, arrJoin, key1, key2, newProperty){
var total = arrJoin.length,
total1 = arr1.length,
ret = {},
i;
for(i=0; i<total1; i++){
if(typeof(arr1[i]) === 'undefined') continue;
ret[arr1[i].Id] = angular.copy(arr1[i]);
ret[arr1[i].Id][newProperty] = [];
}
for(i=1; i<total; i++){
ret[arrJoin[i][key1]][newProperty].push(arr2[arrJoin[i][key2]]);
}
return ret;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment