16.8: Array Functions: filter() - Topics of JavaScript/ES6

This video covers the JavaScript Array higher order function filter().
🎥 Next Video: • 16.9: Array Functions:...
🔗 MDN's Array Documentation: developer.mozilla.org/en-US/d...
🎥 The Modulo Operator with Golan Levin: • Guest Tutorial #6: The...
🎥 Regular Expressions: • 2.1: Introduction to R...
🚂 The Coding Train website: thecodingtrain.com/
💖 Support this channel on Patreon: / codingtrain
🛒 To buy Coding Train merchandise: www.designbyhumans.com/shop/c...
📚 Book recommendations: www.amazon.com/shop/thecoding...
💻 github.com/CodingTrain/Rainbo...
🎥 For an Introduction to Programming: • Start learning here!
🎥 For More Coding Challenges: • Coding Challenges
🔗 p5js.org/
🔗 processing.org
📄 Code of Conduct: github.com/CodingTrain/Code-o...

Пікірлер: 128

  • @JaredSmithTheIntern
    @JaredSmithTheIntern3 жыл бұрын

    I really love that you don't edit out any of the little coding mishapps. It gives me a more realistic example of what coding in the real world is like, with all the little pauses and "what the hell went wrong here?" It's encouraging to know that even people with as much coding experience as you still get stumped now and again.

  • @josevSang
    @josevSang4 жыл бұрын

    i dont know why i burst into laughter one minute after the video, i think i just found my next youtube javascript teacher

  • @volkyomer
    @volkyomer6 жыл бұрын

    best coding teacher i'v ever seen. sincere, natural, informed. thanks again dan..

  • @i_m_veer_singh
    @i_m_veer_singh4 жыл бұрын

    Wow!! what a tutorial.....I like how he starts with a simple and more understandable solution and then put in these new features to make us understand the difference. Love it!!!!

  • @SoloScholar0202
    @SoloScholar0202 Жыл бұрын

    I'm really thankful to you for making this super easy. Your energy never makes any lesson boring. I wish there exists professors like you in my univ. Thanks for rescue captain.

  • @this_rishi
    @this_rishi6 жыл бұрын

    Hey just wanted to thank you for your videos... you truely are a great teacher. I'm currently learning JavaScript and your videos help a lot.

  • @olatunbosunopeyemiademola1761

    @olatunbosunopeyemiademola1761

    Жыл бұрын

    How’s the Programming world now

  • @tariqbakir3359

    @tariqbakir3359

    Жыл бұрын

    @@olatunbosunopeyemiademola1761 🤣🤣

  • @Gbtx6
    @Gbtx6 Жыл бұрын

    I was having a big time understanding how to use filter, and your video made it click almost instantly. Thank you so much. Subbed, because this quality content is what i need in my life

  • @itspaintosee
    @itspaintosee5 жыл бұрын

    Man I just started my first coding job. And I'm struggling. You've been such a great help though. Keep it up dude!

  • @joeyh2541
    @joeyh25414 жыл бұрын

    Thanks for being so animated! I actually learned alot! :)

  • @mo337
    @mo3373 жыл бұрын

    You just got a new subscriber. Thank you a ton for simplifying it so much!

  • @bitcode_
    @bitcode_6 жыл бұрын

    after struggling with this for 2 days, I got it with your video, thank you!

  • @nevillelusimba1689
    @nevillelusimba16895 жыл бұрын

    Arrow functions are just beautiful. So much easier and less prone to side effects.

  • @rimshaarshad7834
    @rimshaarshad78344 жыл бұрын

    Best ever programming video :) no boring coding Just fun learning coding :P

  • @ruthirlekar8632
    @ruthirlekar86325 жыл бұрын

    Thank you !! You're Videos have really helped me.

  • @LorsenHerisdersen
    @LorsenHerisdersen4 жыл бұрын

    I love this guy's energy!

  • @StarlightHeaven
    @StarlightHeaven6 жыл бұрын

    Great videos, great series and great teacher.

  • @sajidakhan9866
    @sajidakhan9866 Жыл бұрын

    Finally I got best coding teacher 😊

  • @MynhDaiK
    @MynhDaiK4 жыл бұрын

    OMG this video appered when i was doing my function exercise

  • @yuvalgal7057
    @yuvalgal70575 жыл бұрын

    you are literally the best teacher i've ever seen, and im registered to Udemy,treehouse and pluralsight, Thank you !

  • @juvenalgonzalez5291
    @juvenalgonzalez52914 жыл бұрын

    I like this guy, gonna look for more of your vids. Good content!

  • @mikepolo7661
    @mikepolo76613 жыл бұрын

    Unusual educational fromat, great job! Thanks for the videos, Daniel, very helpful!=)

  • @leamsi4ever
    @leamsi4ever5 жыл бұрын

    I am following freecodecamp and sometimes I feel that the exercises ask to solve problems when the concepts have not been explained properly and it's very frustrating, even their "Hint" sections are so vague it makes me feel stupid that I can't understand them. This is your first video I've seen and I like your style, I will go back to watch more of your videos!

  • @atamoglannovruzov1189
    @atamoglannovruzov11895 жыл бұрын

    you are just perfect ...thank you very much

  • @SACAS20
    @SACAS203 жыл бұрын

    Dudee! I understand so so the English but your explanation was really good, thanks

  • @codelyslearning
    @codelyslearning Жыл бұрын

    Thank you so much for this educational video, I learned so much.

  • @bibhorkumar2281
    @bibhorkumar22814 жыл бұрын

    Someday,I will meet u,if not ,my life will be worthless,all I will have in life will be because of ur videos..I was 0 in my engineering.u reignited my interest ...till I meet u,❤️.. And sir,if possible,pls add practice questions at the end of the topic or series...anyways,thank u very much..love from india...

  • @anthonyzornig
    @anthonyzornig2 жыл бұрын

    Great style! Always a pleasure.

  • @ziadtoufi5376
    @ziadtoufi53762 жыл бұрын

    Omg first time ive seen a teacher that good u get a sub rn

  • @phillipbarlow2011
    @phillipbarlow20113 жыл бұрын

    Great video, really helped me with my understanding of higher order functions, lost me at 8:45 though lol

  • @lajug2220
    @lajug22206 жыл бұрын

    thank you so much, your videos very helpful :)

  • @GoDXaviA
    @GoDXaviA6 жыл бұрын

    Great series :) i love it

  • @MontyKsycki
    @MontyKsycki6 жыл бұрын

    THANK YOU FOR SHARING!!!! :)

  • @mustafiz012
    @mustafiz0123 жыл бұрын

    Thanks, pretty clean!

  • @Forlorade
    @Forlorade5 жыл бұрын

    I love these and I love you.

  • @A_Lesser_Man
    @A_Lesser_Man4 жыл бұрын

    i believe the period in your sentence is what causes the regex to "detect" a word, and that's why you get the empty array element on the end. you gotta tell the regex to ignore metachars in your string. not sure how to do that in javascript, i code mostly in perl. to treat period (and other metachars as chars and not metachars) you would use /\Q\W+/ that should see the period as an actual period, and exclude it from the results automatically. i haven't checked this, but i'm pretty sure this is right.

  • @khiemgluong
    @khiemgluong3 жыл бұрын

    I wish I could watch and understand all of your videos in a matter of minutes.

  • @GssUpp
    @GssUpp Жыл бұрын

    Thank you so much. You explaining everything so simple. Greetings from Germany!

  • @DigitalMonsters
    @DigitalMonsters6 жыл бұрын

    So is reduce like the multipurpose tool? You can filter with reduce as well just a little longer I guess. let arr = [5, 1, 3, 6, 7, 10, 12]; let filtered = arr.filter(num => !(num % 2)); let reduced = arr.reduce((acc, num) => { if(!(num % 2)) acc.push(num) return acc; }, []); console.log(filtered); console.log(reduced);

  • @wileyr

    @wileyr

    4 жыл бұрын

    Right I’m fairly sure reduce just iterates through the values of the array and passes them through a function, but filter quite literally filters out (in? I don’t know)

  • @riyaazct
    @riyaazct Жыл бұрын

    Such a great video.

  • @rocketsketch
    @rocketsketch6 жыл бұрын

    Hey what's your recording setup? Can you do a video on that? Your videos are entertaining as usual :)

  • @carlostho7403
    @carlostho74032 жыл бұрын

    This man is the best.

  • @NuhAleph
    @NuhAleph5 жыл бұрын

    You are THE best.

  • @arunkumar-mm7qs
    @arunkumar-mm7qs2 жыл бұрын

    Awesome Teaching dude

  • @lycan2494
    @lycan24945 жыл бұрын

    great video! ur very good at teaching :)

  • @thesmartest1919
    @thesmartest19193 жыл бұрын

    thank u so much it was so helpful

  • @dbchrocker
    @dbchrocker2 жыл бұрын

    Nice work 👍

  • @mo337
    @mo3373 жыл бұрын

    Thank you so much

  • @dagmawitewodros5090
    @dagmawitewodros50902 жыл бұрын

    U got my subscription

  • @deepakbhargav7434
    @deepakbhargav74344 жыл бұрын

    THANK YOU SIR

  • @ga7853
    @ga78535 жыл бұрын

    I really liked your video and liked the way you do the teaching, where I can find more video for you, I do not know your name to say whom was teaching this video but it's the video about Javascript 'FILTER'

  • @MrMe-yu7ve
    @MrMe-yu7ve6 жыл бұрын

    Try making a evolutionary fractal tree simulator via evolutionary algorithms but tweaked to suit your needs and to fit the bill of being a tree. I would absolutely see and/or program that!

  • @DaveCollison
    @DaveCollison3 жыл бұрын

    The regex /\ +/ with just a space instead of W gets rid of the trailing item issue without needing filter. And yes, I know that was not the point of what you were doing, but I thought you might like this nugger of information.

  • @charmainetabilas3132
    @charmainetabilas31325 жыл бұрын

    Hi! I am new to JS and was testing the arr.split(/\W.....).filter(....) function and I had the word 'Can't' in my string. It split it into two elements, 'Can', and ' 't'. Is there a way to output it as a single element?

  • @chadlew9593
    @chadlew95933 жыл бұрын

    thank youuu

  • @shivangchaturvedi237
    @shivangchaturvedi2374 жыл бұрын

    Bravo!

  • @reddwarfhead
    @reddwarfhead4 жыл бұрын

    dude.. you're actually.. making sense.

  • @XpLoeRe
    @XpLoeRe2 жыл бұрын

    .filter() goes over each element in the array and copies it into a new array if the predicate is true on the current vaue. thank you!

  • @haciendadad
    @haciendadad5 жыл бұрын

    I'm with you on making code more readable vs terse.

  • @zero11010

    @zero11010

    2 жыл бұрын

    Often readability comes with experience. The first time you see a ternary or an arrow function it may look insane. Then you see it a few more times and it’s no big deal. As an engineer you have to know the syntax. It’s the logic that must be reasonable. You can abuse functionality to do weird things. It’ll work, but it’s bad practice. This makes code less readable.

  • @botleydot
    @botleydot3 жыл бұрын

    Easy way to remove falsey values is `arr.filter(Boolean)`

  • @rlasc84
    @rlasc846 жыл бұрын

    What is the meaning of the underscore argument in map function? I've seen that in some examples in the github page

  • @lborate3543

    @lborate3543

    4 жыл бұрын

    The Underscore _ Identifier A convention has also developed regarding the use of _, which is frequently used to preface the name of an object's property or method that is private. This is a quick and easy way to immediately identify a private class member, and it is so widely used, that almost every programmer will recognize it. This is particularly useful in JavaScript since defining fields as private or public is done without the use of the private and public keywords (at least this is true in the versions of JavaScript used in web browsers - JavaScript 2.0 does allow these keywords). Note that again, as with $, the use of _ is merely a convention and is not enforced by JavaScript itself. As far as JavaScript is concerned, $ and _ are just ordinary letters of the alphabet. Of course, this special treatment of $ and _ applies only within JavaScript itself. When you test for alphabetic characters in the data, they are treated as special characters no different from any of the other special characters.

  • @MrCk0212
    @MrCk02123 жыл бұрын

    So behind these higher order functions, do they just use for-loop or something more special?

  • @zero11010

    @zero11010

    2 жыл бұрын

    Behind the scenes they would use a for loop. Not all are the same. Some of these like .find() does not iterate until the end. When it finds what it’s looking for it will return early. Makes it more efficient than a filter or a forEach or a map. Additionally, a lot of these create a new array. There are space and time costs associated with that.

  • @Bomb4stic
    @Bomb4stic6 жыл бұрын

    Hello i like your videos so much and your explanation its high keep up, but I have a question I am using filter, reduce and map to a function but cannot filter things by the date, I am using TypeScript in Angular 4, here is my code, if you can take time to answer of course. xport function getTotalYearCosts(valueItem: ValueItem, allCosts: Map): TotalCosten { const totalYearCosts = { planned: 0, actual: 0 }; totalYearCosts.actual = valueItem.actualCostIds .map(costId => allCosts.get(costId, emptyCosts()).costs) .filter(costs => costs.created) .reduce((reduction, costs) => reduction + costs, 0); Best Regards

  • @pratikkolge2490
    @pratikkolge24906 жыл бұрын

    Zero is also falsy value. If the array contains zeroes they will be removed too..

  • @codewithpranavjeet
    @codewithpranavjeet4 жыл бұрын

    What if the Goal is to filter huge array 10^6 which is being provided by API. Please let me know best alternative or approach for array to get O(n) .

  • @zero11010

    @zero11010

    2 жыл бұрын

    How long it takes will depend on the work being done. You have to loop over every element. You will need to make a new array. The work required to identify what to place into the new array is the only thing that can make this more costly. If you have to reference another array this won’t be O-N. Unless you can convert the second array to a set or object to give you constant look up … or maybe a heap or a tree to give you O-Log access.

  • @SruthiSNair
    @SruthiSNair3 жыл бұрын

    Hi, can the filter function program be written using for...of loop?

  • @zero11010

    @zero11010

    2 жыл бұрын

    Filter is higher order. You can pass it any function. The function you pass it can use a for of loop. 👍

  • @beingian
    @beingian3 жыл бұрын

    How would you approach this problem if you had to filter an array based on more complex conditions, such as if a string contains a number or a symbol? i.e filtering an array of strings which are passwords, where only strings containing numbers and symbols are valid?

  • @zero11010

    @zero11010

    2 жыл бұрын

    Write a function to check if one string matches the results. Call that function with filter. const heroFunc = str => (do work); arr.filter(heroFunc) So long as heroFunc looks at a string and returns true if it meets requirements and false otherwise, that will iterate over each element in your array and run the heroFunc on it. If it returns true, then it goes into the new array of filtered elements to be returned.

  • @MultiPerplexedDude
    @MultiPerplexedDude5 жыл бұрын

    does writing this code in a more cryptic but shorter form make it faster in browser to execute? or is the difference nihil?

  • @TheCodingTrain

    @TheCodingTrain

    5 жыл бұрын

    I think it might actually be slower! From what I understand, these features do not increase performance.

  • @MultiPerplexedDude

    @MultiPerplexedDude

    5 жыл бұрын

    @@TheCodingTrain ooh good to know! I might need to do some more research on it then just go be sure :)

  • @vaibhavm1986
    @vaibhavm19865 жыл бұрын

    X => X .... How did it bypass undefined?

  • @okoiful
    @okoiful6 жыл бұрын

    In FP you dont reassign a new value to a var.. you create a new one..its about the inmutability of data...

  • @unnamed49
    @unnamed492 жыл бұрын

    9:06 using filter for that is a total overkill. Just continue using regex to turn it into an array without an empty value like this: s.split(/\s+/);

  • @jameskobe1716
    @jameskobe17165 жыл бұрын

    If i want to chain map and filter , do i have to use filter before map ?

  • @bibhorkumar2281

    @bibhorkumar2281

    4 жыл бұрын

    It may even not matter as this question was posted 1 year back, but first we will filter,then use map...

  • @zero11010

    @zero11010

    2 жыл бұрын

    You can use them in any order. You have stuff …. Do you want to make a new array with the same number of elements? Map them. You have stuff … do you want to eliminate some of the elements? Filter them. If you need to run a function on everything to get it into the right state before you filter …. Map then filter. If stuff is already in the right state for you to filter and you need to run a function on the filtered things (like … who has today as their birthday? Wish those people happy birthday. That saves work because otherwise you would wish everyone happy birthday then filter down to the people who have today as a birthday) What you need to do will depend on your situation.

  • @filipkendes1866
    @filipkendes18666 жыл бұрын

    How did you make localhost. I watched your video, but still couldn't make it... I installed plugin for atom (atom-live-server) but when i open server on the right side i just get sample of my code which i wrote in atom.

  • @TheCodingTrain

    @TheCodingTrain

    6 жыл бұрын

    This workflow video might help: kzread.info/dash/bejne/eo5oppWwdLXHlcY.html Also: sublime text: kzread.info/dash/bejne/h3d83M6OmaeqYZM.html atom editor: kzread.info/dash/bejne/lmeDxaieqMifec4.html

  • @filipkendes1866

    @filipkendes1866

    6 жыл бұрын

    great job, That video helped me a lot. Love your effort

  • @MeasuresDesperately
    @MeasuresDesperately4 жыл бұрын

    what would you do if the value inside of the array your filtering is another array? I have an array called cells and within the cells array are 323 arrays all containing 3 values which is int1, int2, bool. im trying to filter out any array within the cells array thats bool value is true.

  • @zero11010

    @zero11010

    2 жыл бұрын

    arr.filter( subArr => subArr[2] === true) You have matrix. The array has a bunch of elements. Each of those elements is an array. If each of those ALWAYS has a 3rd element (index 2) that is a Boolean and you want the true values …. Iterate through the matrix (with filter) At each element check index 2 to see if that element at index true is a Boolean of true.

  • @vishwakneelamegam9479
    @vishwakneelamegam94793 жыл бұрын

    what algorithm is behind filter function

  • @zero11010

    @zero11010

    2 жыл бұрын

    It’s pretty simple. It would be exactly what you think. Make an array to return. A for loop. Run function on element If the output is true Place element into array to return. When loop is complete return array. There isn’t another way to do it. The code isn’t magic.

  • @ConsulthinkProgrammer
    @ConsulthinkProgrammer3 жыл бұрын

    Thanks. Sir, suppose I have script like this: var leaveFilter = data.filter(data => {return data[1 == "Annual Leave" || data[1] == "Vacation leave" || data[1] == "Sick" || data[1] == "Important leave"}); How if I want make some iteration, or loop perhaps, so I just have to make that filter in array like this: filters = [ "Annual Leave", "Vacation leave", "Sick", "Important leave"] Which later I want that I could use that filters variable to do some iteration/loop in filter method above. Could help to you break this problem?

  • @zero11010

    @zero11010

    2 жыл бұрын

    Bad habit to call a thing data, then iterate over what data contains and call each thing within data by the same variable name. const leaveTypes = new Set([‘vacation’, ‘sick’ ….]); const onLeave = people.filter(person => leaveTypes.has(person[2])); Sorry I’m on my phone and I can’t refer to your question while answering. Put the strings that are the status you’re searching for in a set. This gives you constant look up for them. One computation instead of checking 3 things iteratively. If that sounds scary you could instead use .find() or .includes() but those take longer to run. Once you have your set Array.filter(element => set.has(element[index])) You’re saying …. I’m looking over an array. I’m looking at an element. I want to know if this element at this index has anything inside this set of data.

  • @ConsulthinkProgrammer

    @ConsulthinkProgrammer

    2 жыл бұрын

    ​@@zero11010 Thanks for your answer. I have solved the problem and got the solution from another comment on another channel about a year ago, here it is: var leaveFilter = data.filter(data => {return [ "Annual Leave", "Vacation leave", "Sick", "Important leave"].includes(data[1])});

  • @zero11010

    @zero11010

    2 жыл бұрын

    @@ConsulthinkProgrammer that works. With that soliton you have a nested loop you’ve built. With so few things to iterate through it doesn’t matter a ton. Using a set would offer better performance. But, both work!

  • @ConsulthinkProgrammer

    @ConsulthinkProgrammer

    2 жыл бұрын

    @@zero11010 thanks again for your tips, I will learn and practice to use set also for this case :)

  • @nirajlakhadive
    @nirajlakhadive3 жыл бұрын

    return arr.filter(Boolean); any please explain how the above code is working

  • @zero11010

    @zero11010

    2 жыл бұрын

    Filter runs a check on each element to see if it’s true. If it is true, it is placed into a new array and returned. So this will loop over an array. It will look at an element and run Boolean on it. That will compare return true if the element is truthy. 1, true, ‘Cat’, [9] are truthy An empty string, the number 0, undefined, null and false are all falsey type elements. Run the code in node.

  • @hiteshsofat8458
    @hiteshsofat84584 жыл бұрын

    what is exact difference between map and filer if i write this var a = [2,5,6,7,8]; a = a.map(x => x % 2 == 0); console.log(a) or var a = [2,5,6,7,8]; a = a.filter(x => x % 2 == 0); console.log(a) both are same in output.

  • @zero11010

    @zero11010

    2 жыл бұрын

    Start with the MDN docs. Those are not the same in output. Map runs a function on each element and returns an array of the same size. In your example you make a new array with the same size and each element is a Boolean. In the second array you filter out the odd numbers. You could use forEach to do what either of those do.

  • @brucelee7782
    @brucelee77825 жыл бұрын

    4:00 Wtf does function isEven(num){ return(num%2==0) } even mean? Is there a hidden if condition inside (num%2==0)??? I understand the % operator but I dont understand this shortcut for return....

  • @jcjobin

    @jcjobin

    5 жыл бұрын

    num%2 where "%" is modulus, meaning if the number is divisible by 2 and the remainder is 0, then the condition is True. So return true. But notice later at 5:12 he says x%2==1, meaning if the remainder is 1, then return True. Remainder 1 would be any odd numbers. Hope that helps a bit

  • @brucelee7782

    @brucelee7782

    5 жыл бұрын

    @@jcjobin Hey man, thanks for the reply. My question is directed towards why there seems to be a hidden "if condition" when you write (num%2==0) after return because you didn't actually write the "if" words there. My question is not directed towards what is the modulus operator or how it works.

  • @jcjobin

    @jcjobin

    5 жыл бұрын

    @@brucelee7782 Oh I see, yeah, the statement "num%2==0" will result to either "true" or "false", so returning a boolean is all we want to do in that case

  • @brucelee7782

    @brucelee7782

    5 жыл бұрын

    @@jcjobin my question is WHY will it? Nevermind I found out that it is because of the == operator. Kinda obvious but I never considered putting this expression after the return statement.

  • @malibaturhan
    @malibaturhan2 жыл бұрын

    you can think like upper filter come with us and drainage goes

  • 4 жыл бұрын

    You don't have to use `not word - \W` specifier on Regex for the purpose of split by space character. You can use `space = \s` for that. > "Hello darkness \t\t\t my old \tfriend".split(/\s+/).join('_') > "Hello_darkness_my_old_friend"

  • @teacherrussell5206
    @teacherrussell52063 жыл бұрын

    My favorite fish is now gefilter fish.

  • @cloroxbleach861
    @cloroxbleach8616 жыл бұрын

    hello

  • @azampasha6020
    @azampasha60203 жыл бұрын

    Ruj k shokha!

  • @sanukumar306
    @sanukumar3063 жыл бұрын

    You get empty string because of that ending full stop symbol 😀

  • @chrisjoseph6491
    @chrisjoseph6491 Жыл бұрын

    ur a goat

  • @halilualiyu6152
    @halilualiyu61523 жыл бұрын

    *I give all thanks to WAPTECS and twitter for helping me fix my Göogle account*

  • @michaelrooze278
    @michaelrooze2783 жыл бұрын

    This method works in the opposite way that it should...very frustrating......they should just rename it to "keep" because you are creating a condition that determines what elements you want to KEEP and not the ones you want to get rid of.....Correct me if im wrong

  • @josebarona271
    @josebarona2715 жыл бұрын

    I want u to be my dad

  • @thedonsky5092
    @thedonsky50923 жыл бұрын

    the last part lost me with the /\W+/

  • @sindygoro3800
    @sindygoro38003 жыл бұрын

    My account got disabled for nó reason, then a friend introduce me to WAPTECS who got my accóunt recovered successfully,🤗

  • @EricJost
    @EricJost6 жыл бұрын

    Hate those grimy arrays.

  • @DavidIFernandezMunoz
    @DavidIFernandezMunoz3 жыл бұрын

    I think I hate this guy. For a variety of reasons. First, because he makes everything look easy, and it isn't. Second, because I like to know but I hate to learn. Third, because I hate people that know more than me. Fourth, because he knows more than me due to... intelligence, practice, experience, curiosity and persistence. But, good teacher. I will not watch more than another 70 or 80 of his videos. Give or take a few hundred.