Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Arrays exist in every programming language. It's a data structure best suited for storing multiple values. And, for doing various operations on these values, often called as a collection.
It's always best to learn by doing. Take a look at the below code example, study and execute it step by step.
Let's learn how to utilize array methods to do useful operations on the entire collections.
Useful array methods & avoiding loops
Changing original array items, pushing to it results in mutating which can introduce unwanted, side effects and makes code much more difficult to maintain. Let's aim for a declarative, functional approach with immutability in mind. Go through the below examples to see how we can easily achieve that with less code and more semantics.
Assignment: Multiply all numbers by 2.
✅ Map numbers in an array:
Assignment: Remove all numbers less or equal to 10.
✅ Filter numbers in an array:
Assignment: Sum all numbers.
✅ Reduce numbers to create a sum:
Assignment: Find index of number 15.
✅ Find index by using an
Assignment: Check if all numbers are greater or equal to 10.
✅ Check if condition is true to all numbers:
Assignment: Check if any number is greater or equal to 10.
✅ Check if condition is true to any number:
Assignment: Check if number 15 is included in the numbers array.
✅ Check if number is included:
I described couple of more methods, techniques to work with arrays, example below:
I have lots of fun with immutability and enjoy it to the max. Don't remember when I wrote a loop last time. Mostly working on Frontend tho, might be totally different when working with Backend as it's all about optimizations then. Find your balance.
Declarative, functional programming is cool but there is nothing wrong with mutations too. Using
breakor loops might be necessary, don't limit yourself to one style. It's all about conventions when working in a team and if you mostly work solo, find what suits you the best.
Big thanks for reading the article, you're awesome! 🙇♂️
You can also find me on:
Thanks for all the support. ❤️
THE GUIDE TO BEAT FRONTEND INTERVIEW
Let's build a community that will help each other.