So I am working out of a previous question I asked here, in which I talked about making a history timeline from a JSON file using AngularJS. Essentially, the JSON file contains a bunch of HISTORY EVENTS object, each of them containing an ID called "theDate" to indicate the date at which these unique events took place. I want to sort all of the events into their specific DECADES for navigation purposes later in the view and using CSS.
I'm struggling with creating a multidimensional array whose structure should be something like this (this should be the MASTER array):
[[all of 1960s events],[all of 1970s events], [all of 1980s events]...]
...In which each of those specific arrays within the MASTER array contains event objects for that specific decade. (For example, for the 1960s array, the events should contain the years [ 1961, 1963, 1969,etc.].
Working with AngularJS, I have my working code here:
var events = $scope.events;
function decadeSort(){
var year;
var arrayOfYears = [];
for(var i = 0; i<events.length; i++){
var date = new Date(events[i].theDate);
year = date.getFullYear();
var yearToString = year.toString();
var yearToDecade = yearToString.substring(0,3).concat("0");
arrayOfYears.push(yearToDecade);
}
console.log(arrayOfYears);
};
decadeSort();
The arrayOfYears array prints out all the YEAR of the 267 event objects according to their respective DECADE like this:
["1960","1960","1970","1970","1970","1980","1980","1990","1990","2000","2000"..]
With some of the string objects in THAT array repeat, I was hoping to create new arrays WITHIN that array based on which objects are the same strings. I don't know how to write this loop, so any insight and help would be greatly appreciate.
Thank you so much!
Using the sample-event you posted, the following is a simply way to group-by decade:
var grouped = {};
events.forEach(function (event) {
var decade = Math.floor((new Date(event.theDate)).getFullYear() / 10) * 10;
if (typeof grouped[decade] === 'undefined') {
grouped[decade] = [];
}
grouped[decade].push(event);
});
console.log(grouped);
It's using forEach which you might need to change, if you're targeting a browser that does not support it.