I'm trying to take an array (for an example, an array of years) and then make a new array of sub-arrays which tells, firstly, the unique element in the original array and, secondly, how many time it was repeated.
For example, lets say I start of with an array of numbers [1999, 1999, 2000, 2005, 2005, 2005, 2015]
I would like my function to return an array like [[1999, 2], [2000, 1], [2005, 3], [2015, 1] ]
because the year 1999 was repeated twice, the year 2000 was was not repeated, the year 2005 was repeated three times, etc.
I can successfully make a new array that removes the duplicates, but Im getting some weird behavior when it comes to making my sub-arrays.
EDIT
Here was my own faulty solution, in case anyone wants to point out what i did wrong.
var populateYearsList = function(yearsDuplicate){
var uniqueYears = [];
for (var i=0; i < yearsDuplicate.length; i++){
if(uniqueYears.indexOf(yearsDuplicate[i]) == -1){
uniqueYears.push(yearsDuplicate[i])
} else {
console.log("duplicate found") };
}
console.log (uniqueYears)
};
I ran into the problem of trying to change uniqueYears.push(yearsDuplicate[i])
into uniqueYears.push([ yearsDuplicate[i], 1 ])
and then trying to replace my console.log into some sort of incremented counter.
It is as easy as:
EDIT NOTE:: FIXED the previous solution which might introduced duplicate element.