block by tomgp 2b0bb77a657450609a9f

Split an array

Split an array of elements ‘e’ into a set of arrays based on a function f(e)

function splitOn(array, keyFunction){
    if(!keyFunction) keyFunction = function(d,i){ return i; };
    var splitUp = {};

    array.forEach(function(d,i){
        var key = keyFunction(d,i);
        if(!splitUp[key]) splitUp[key] = [];
        splitUp[key].push(d);
    })
    return splitUp;
}

so for example if the elements have a date property you could get a set of arrays by year…


var years = splitOn(data, function(d){
    if(d.date){
        return d.date.getFullYear();
    }
    return 'no date';
});

the resulting object …

Object { 
  '2009': Array[41], 
  '2010': Array[43], 
  '2011': Array[51], 
  '2012': Array[40], 
  '2013': Array[36], 
  'no date': Array[8], 
  '2014': Array[23], 
  '2015': Array[18] 
}

So you may perfer an array of array in which case maybe…

var arrayByYear [];

Object.keys(years).forEach(function(d){
  arrayByYear.push(years[d])
});