DEV Community 👩‍💻👨‍💻

Mayank Arya
Mayank Arya

Posted on • Originally published at Medium

How I filter my arrays.

Javascipt has a very active community and that provides developers with a plethora of options in when it comes to solving a simple problem.

Although I myself love to use libraries like lodash or underscore when it comes to iterating on arrays or objects. I suppose for a beginner being able to read and understand MDN docs is really really important to get that strong foundation.

MDN however has a tendency of being a tad bit technical, which may or may not intimidate beginner coders.

Anyways, this article is here to simplify or simply put forward a few of the everyday use-cases.

Filtering an array
So, keeping aside the libraries I'm going to show you a set of functions which you will help you filter an array in different ways and are supported natively by the language.

  • Find a value: Use array.find(callback) : It will stop and return the value as soon as the condition is satisfied.
  • Filter on the basis of a condition Use array.filter(callback) : It will iterate through the whole array and return a new array with only those elements which satisfy the condition.

filter can be used for find use-case but filter will iterate the whole array/list even if the first element was the only one that satisfied our condition

  • Find if atleast one element in list satisfies our condition Use array.some(callback) : It will stop and return a boolean value based on if the condition is satisfied (does not iterate the whole list).

some has its own use case because find will return you the value but if you just want to check, a boolean value is well better just to maintain a standard practice

  • Find if all the elements in list satisfy our condition Use array.every(callback) : It will iterate through the complete array and return a boolean according to the condition i.e. true if all elements satisfy our condition false if any one of the elements do not satisfy our condition

Examples of all the above written functions

Top comments (0)

Want to Create an Account?
Now it's your turn!
 
🗒 Share a tutorial
🤔 Reflect on your coding journey
❓ Ask a question

Create an account to join hundreds of thousands of DEV members on their journey.