D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
kcsluis
Full window
Github gist
Data Manipulation
<!DOCTYPE html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> </style> </head> <body> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script> <script> d3.tsv("barley.tsv", ready); function ready(error, data) { if (error) return console.warn(error); // declare a function function functionName(functionVariables) { // foo }; // anonymous functions are used often var anon = function (d) { return d.foo; }; // these functions can also return an index var anonIndex = function (d, i) { return d.foo+i; }; // use .map to extract from a larger data set var yields = data.map(function (d) { return d.yield; }); // use .filter to select data conditionally var grandRapidsData = data.filter(function (d) { return d.site == 'Grand Rapids'; }); // use .reduce to sum - (a, b) is critical var totalYields = yields.reduce( function (a,b) { return a + b; }); // use .sort to order data = (a,b) is critical data.sort(function (a,b) { return a.yield - b.yield; }); // map and sort together to dedupe var allVarieties = data.map( function (d) { return d.variety; }); var allVarietiesDeduped = d3.set(allVarieties).values(); // min, max, extent (extent returns array with two values) var yieldsMin = d3.min(yields); var yieldsMax = d3.max(yields); var yieldsExtent = (d3.extent(data, function (d) { return d.yield; })); // rounding var rounded = Math.round(23.2); var roundedDecimals = (23.42422).toFixed(2); // reduce w. a ternary operator var sumYieldsOver50 = yields.reduce(function (a, b) { return (a > 50) ? a + b : b; }); data.forEach( function(d) { // .split, returns array of characters split by character d.split = d.yield.split("."); // .replace d.replace = d.yield.replace(".", ","); // trim whitespace d.trim = d.site.replace(/\d/g,'').trim(); // substring selection var str = d.site; var strSubstring = str.substring(0, str.length); }); // date var s = [0,2]; var date = new Date(s[0],(s[1]-1)); // month index is 0 based (jan is 0, feb is 1) // day is 1 based // will add commas function formatNumber (num) { return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") }; function addCommas(nStr) { nStr += ''; var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }; // for x in y (x can be whatever you like) for (yield in yields) { // console.log(yield); }; // other for loop allVarietiesDeduped.forEach(function (d) { // console.log(d); }); }; </script>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js