Skip to content

Instantly share code, notes, and snippets.

@tomgp
Created November 9, 2015 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomgp/2b0bb77a657450609a9f to your computer and use it in GitHub Desktop.
Save tomgp/2b0bb77a657450609a9f to your computer and use it in GitHub Desktop.
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])
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment