Hello and welcome to my first dev.to blog post! Recently I've been working with react a lot and I wanted to review the filter()
function for those that may need a little help with it!
As I'm proceeding with this tutorial I will be using the console. First, I'm going to start by creating and array on peoples names const names = ["Randy", "Kristy", "Brady", "Toby", "Kashton"]
ok, sweet now we have some people in our names array. Now I'm going to filter the array to see if we can find a person from our array that pass a particular test. Let's check it out. names.filter(name => name.includes('R'))
Here I am calling filter on the names array and looking for anything that matches the letter 'R'. Here are the results ["Randy"]
notice we are only getting the results for the capital letter R not the other names that have 'r'. So what if we wanted to find both 'R' and 'r'? Let's see how we can make that work. If we try something like 'names.filter(name => name.includes('R', 'r'))will this give us the results for 'r' and 'R'? nope, that does not work. Let's try this
names.filter(name => name.includes('R') || name.includes('r'))Alright, cool this is what we need, now we have
["Randy", "Kristy", "Brady"]` as our filtered results.
Now that we have seen a very simple example of filtering in JS, let's take a look at a simple sorting example. We will be using the same example from the filtering example. We can sort alphabetically very simply by names.sort()
our results are: ["Brady", "Kashton", "Kristy", "Randy", "Toby"]
Now let's say you want this in the opposite order, how can we achieve this? Let's try a slightly different method to achieve this. names.reverse()
results: ["Toby", "Randy", "Kristy", "Kashton", "Brady"]
Now I want to add a name to my array. I'm going to do that by names.push("Ashley")
now lets sort again names.sort()
results: ["Ashley", "Brady", "Kashton", "Kristy", "Randy", "Toby"]
Next let's remove someone from our array. names.pop("Toby")
results: ["Ashley", "Brady", "Kashton", "Kristy", "Randy"]
These are some simple way to filter and sort your arrays in Javascript. Obviously there lot's more you can do with these methods but this is a start and you can accomplish quite a bit with just learning these few basic methods. To learn more about array methods in Javascript, I recommend visinting "W3 Schools
Thank you very much for reading my blog and happy coding!
Top comments (2)
good work... 👍👍
Thanks Anwar!