DEV Community

Cover image for Getting the frequency of an element in an array in JavaScript

Getting the frequency of an element in an array in JavaScript

Perelyn-sama on December 06, 2020

First of all, what is frequency? According to Wikipedia, it's" the rate at which something occurs over a particular period of time or in a given sa...
Collapse
 
kais_blog profile image
Kai •

There's no need for nums.map(e => Number(e)). Here, you are transforming numbers to... well, numbers. You can skip this step. If you really want to convert them to strings you should use either String(e) or e.toString().

Collapse
 
perelynsama profile image
Perelyn-sama •

I'm sorry It's a typo, I originally wanted to write String(e). Thanks for pointing out to me

Collapse
 
mzaini30 profile image
Zen •

You can change Number(e) with +e

Collapse
 
keogami profile image
keogami •

Thats too hacky and non intuitive i.e. not readable. As a simple rule you must avoid being clever because readable code is always better than clever code 😊

Collapse
 
perelynsama profile image
Perelyn-sama •

True, simple code is good code.

Collapse
 
perelynsama profile image
Perelyn-sama •

Thanks for the pointer.

Collapse
 
rishitkhandelwal profile image
Rishit Khandelwal •

We could just use Array.reduce

Collapse
 
perelynsama profile image
Perelyn-sama •

Yeah, there's more that one way to skin a cat

Collapse
 
rishitkhandelwal profile image
Rishit Khandelwal •
const count=(i,w)=>i.reduce((a,v)=>v==w?a+1:a,0)
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
perelynsama profile image
Perelyn-sama •

Thanks!

Collapse
 
chaugiang profile image
Nguyen Tran Chau Giang •
const letters = ["a", "b", "c", "a", "b", "c", "a", "b"];
const countLetters = letters.reduce((m,n)=>({...m, [n]:-~m[n]}),{})

// For nums, it is the same
Enter fullscreen mode Exit fullscreen mode
Collapse
 
perelynsama profile image
Perelyn-sama •

Wow thanks, that's awesome and shorter

Collapse
 
chaugiang profile image
Nguyen Tran Chau Giang •

no problems, keep learning !

Collapse
 
bytebodger profile image
Adam Nathaniel Davis •

Why would you need to do this any differently for numbers vs strings?? The first example (the one that you show as being "for string elements") works just fine if you pass in the array of numbers.

Collapse
 
perelynsama profile image
Perelyn-sama •

Wow, I never realized that. Thanks for the pointer, I'll the remove the 'For numbers' part.

Collapse
 
angelainniss profile image
Angela Inniss •

Thanks for this. This is good for beginners like me as it says in the tags. Some of the other suggestions are cool too but a bit more confusing :)

Collapse
 
keogami profile image
keogami •

Ngl the "for numbers" part is stupid

Collapse
 
perelynsama profile image
Perelyn-sama •

That I agree with, thanks for your feedback