DEV Community

Cover image for Useful JS array methods to level up your game!

Useful JS array methods to level up your game!

Sanjeev Sharma on August 02, 2020

Hi there! Today, I'll be sharing some useful JS array methods that I use daily. These methods will surely level up your game as a beginner. 💪 Let'...
Collapse
 
wicked7000 profile image
Wicked

Great post! I would be wary about using reduce though it's often advised against usage especially from most eslint rulesets. Often due to the fact (as you even mentioned in the post) that reduce looks hard and can be hard to understand.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

"X looks hard" is not a good reason not to use something. reduce (or fold, or inject, or whatever other programming languages call it) is an incredibly useful function and should be used.

Collapse
 
thesanjeevsharma profile image
Sanjeev Sharma

Thank you.

And reduce() is actually very simple, once you get it. My life has been a lot easier with reduce().

Collapse
 
wicked7000 profile image
Wicked

I do agree that reduce isn't that complicated but I was trying to just explain (which I may have done badly) that instead of using reduce its often better to avoid it and using something simpler to understand. For example using .sum is a lot better than using reduce because it's self descriptive in what it does.

That doesn't mean there isn't a usecase for reduce I'd just use it sparingly. But of course that's just my opinion!

Collapse
 
cairnswm profile image
William Cairns

I find staticMap() a very underrated function

Collapse
 
thesanjeevsharma profile image
Sanjeev Sharma

I am not sure what you're talking about. Can you provide a reference? I'd love to read about it.

Collapse
 
cairnswm profile image
William Cairns

Sorry, its flatMap

developer.mozilla.org/en-US/docs/W...

The array.map() returns a single item per item in the array. with flatMap you can return multiple or no items per item in the array you are iterating over

Thread Thread
 
thesanjeevsharma profile image
Sanjeev Sharma • Edited

Yes! I've used it recently. But I think it's for specific cases only. Not something you'd use every day. But again, really useful and a pretty one. ✌️

Maybe, I'll make a Part 2 for these kinds of methods. 😉

Collapse
 
harshjains profile image
Harsh • Edited

Just want to highlight something in Array filter example :
adultsOnlyList & noMenList will return array of object if you want to print name then you need to map that array one more time like this :

const adultList = persons.filter( person => person.age > 18).map( person => person.name);
// output of adultList --> [ 'Mark', 'Julia' ]
it will return array which will contain only name of person which are above 18.

Collapse
 
thesanjeevsharma profile image
Sanjeev Sharma

Oh yeah! My bad.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

*cries in NodeList*