In Javascript, I\'m trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each
Solution using a map with O(n) time complexity.
var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9]; const countOccurrences = (arr) => { const map = {}; for ( var i = 0; i < arr.length; i++ ) { map[arr[i]] = ~~map[arr[i]] + 1; } return map; }
Demo: http://jsfiddle.net/simevidas/bnACW/