Create an array of sub-arrays with the value of an element and the number of times it has repeated in JavaScript -
i'm trying take array (for example, array of years) , make new array of sub-arrays tells, firstly, unique element in original array and, secondly, how many time repeated.
for example, lets start of array of numbers [1999, 1999, 2000, 2005, 2005, 2005, 2015]
i function return array [[1999, 2], [2000, 1], [2005, 3], [2015, 1] ]
because year 1999 repeated twice, year 2000 was not repeated, year 2005 repeated 3 times, etc.
i can make new array removes duplicates, im getting weird behavior when comes making sub-arrays.
edit
here own faulty solution, in case wants point out did wrong.
var populateyearslist = function(yearsduplicate){ var uniqueyears = []; (var i=0; < yearsduplicate.length; i++){ if(uniqueyears.indexof(yearsduplicate[i]) == -1){ uniqueyears.push(yearsduplicate[i]) } else { console.log("duplicate found") }; } console.log (uniqueyears) };
i ran problem of trying change uniqueyears.push(yearsduplicate[i])
uniqueyears.push([ yearsduplicate[i], 1 ])
, trying replace console.log sort of incremented counter.
it easy as:
var input = [1999, 1999, 2000, 2005, 2005, 2005, 2015]; var uniq = []; input.foreach(function(n){ if (uniq.indexof(n)<0) uniq.push(n); }); var output = uniq.map(function(n){ return [n, input.filter(function(m){ return m == n }).length] });
quick explanation how works
given input array, map its unique version new array mapping:
element ---> [ element, the number of occurrences in original array ]
edit note:: fixed previous solution might introduced duplicate element.
Comments
Post a Comment