Created
April 9, 2015 15:10
-
-
Save mrosenberg/9d18131ecfa5c6973200 to your computer and use it in GitHub Desktop.
Zipper method for adding chart values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Tested in node v0.10.34 | |
** This will probably fail in older versions of IE, because IE. | |
function zipper(/** someArrays, {key:name,value:name} **/) { | |
var args = Array.prototype.slice.call(arguments), | |
arrs = args.slice(null, args.length - 1), | |
item = args.slice(-1)[0], | |
keys = []; | |
if ('[object Object]' !== Object.prototype.toString.call( item )) throw 'Last Argument needs to be an object {key:name,value:name}'; | |
// We need an array of unique keys | |
function uniq(array) { | |
var ret = []; | |
array.forEach(function(k) { | |
if (ret.indexOf(k) < 0) { | |
ret.push(k); | |
} | |
}); | |
return ret; | |
} | |
// Get all keys | |
arrs.forEach(function(arg) { | |
arg.forEach(function(datum) { | |
keys.push(datum[item.key]); | |
}); | |
}); | |
return uniq(keys).map(function(key) { | |
var retn = {}, | |
vals = []; | |
arrs.map(function(array) { | |
return array.filter(function(object) { | |
return key === object[item.key]; | |
}) | |
.map(function(array) { | |
vals.push(array[item.value]); | |
}); | |
}); | |
retn[item.key] = key; | |
retn[item.value] = vals.reduce(function(cur, prev) { | |
return cur + prev; | |
}, 0) | |
return retn; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment