Skip to content

Instantly share code, notes, and snippets.

@visualjeff
Created October 7, 2016 00:09
Show Gist options
  • Save visualjeff/b52309b99e31fb2a3351113a3c300dcd to your computer and use it in GitHub Desktop.
Save visualjeff/b52309b99e31fb2a3351113a3c300dcd to your computer and use it in GitHub Desktop.
I'm tired of for loops inside for loops for array hashing...
'use strict';
var userRolesInNewApp = [
{displayName: 'tester', value: 't'},
{displayName: 'hacker', value: 'h'},
{displayName: 'manager', value: 'm'}
];
var object = {
appRoles: [
{displayName: 'tester', value: 't'},
{displayName: 'developer', value: 'd'},
{displayName: 'admin', value: 'a'},
{displayName: 'user', value: 'u'},
{displayName: 'manager', value: 'm'}
]
};
console.log('=== version 1 using for loops. Over ten lines of code =============================');
var rolesToAdd = [];
for (var i = 0; i < (userRolesInNewApp.length); i++) {
var existingRole = false;
for (var j = 0; j < object.appRoles.length; j++) {
if ((userRolesInNewApp[i].displayName == object.appRoles[j].displayName) && (userRolesInNewApp[i].value == object.appRoles[j].value)) {
existingRole = true;
break;
}
}
if (existingRole) {
rolesToAdd.push(userRolesInNewApp[i]);
};
}
console.log(`${JSON.stringify(rolesToAdd, null, 2)}`);
console.log('=== version 2 using a filter and find function. 1 line of code =============================');
rolesToAdd = userRolesInNewApp.filter((userRole) => object.appRoles.find( (appRole) => userRole.displayName == appRole.displayName && userRole.value == appRole.value ) !== undefined);
console.log(`${JSON.stringify(rolesToAdd, null, 2)}`);
console.log('=== version 3 using a filter and find function. 1 line of code (streched over 3 lines) =============================');
rolesToAdd = userRolesInNewApp.filter((userRole) => object.appRoles.find( (appRole) => {
//Conditional check below...
return userRole.displayName == appRole.displayName && userRole.value == appRole.value;
}) !== undefined);
console.log(`${JSON.stringify(rolesToAdd, null, 2)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment