I am seeking a way to transform a one-dimensional array into a frequency dictionary in JavaScript. The array elements should serve as keys, while their frequencies act as values.
Take, for example, the Python script below, which generate a list of 1024 random numbers ranging from 0 to 255, and then count their occurrences:
import random
from collections import Counter
sorted(Counter(random.randbytes(1024)).items(), key=lambda x: -x[1])
I can achieve the same in JavaScript, albeit not as succinctly:
var numbers = Array.from({length: 1024}, () => Math.floor(Math.random() * 256))
var counter = Object()
for (let number of numbers) {
if (counter.hasOwnProperty(number)) {counter[number] += 1}
else {counter[number] = 1}
}
Object.entries(counter).sort(([,a],[,b]) => b-a)
Is there an easier way to accomplish this task more concisely?