Тёмный

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

The Coding Train
Подписаться 1,7 млн
Просмотров 130 тыс.
50% 1

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...

Опубликовано:

 

8 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 128   
@JaredSmithTheIntern
@JaredSmithTheIntern 3 года назад
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
@josevSang 5 лет назад
i dont know why i burst into laughter one minute after the video, i think i just found my next youtube javascript teacher
@volkyomer
@volkyomer 6 лет назад
best coding teacher i'v ever seen. sincere, natural, informed. thanks again dan..
@i_m_veer_singh
@i_m_veer_singh 4 года назад
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.
@sajidakhan9866
@sajidakhan9866 Год назад
Finally I got best coding teacher 😊
@nevillelusimba1689
@nevillelusimba1689 5 лет назад
Arrow functions are just beautiful. So much easier and less prone to side effects.
@this_rishi
@this_rishi 6 лет назад
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
How’s the Programming world now
@tariqbakir3359
@tariqbakir3359 Год назад
@@olatunbosunopeyemiademola1761 🤣🤣
@LorsenHerisdersen
@LorsenHerisdersen 4 года назад
I love this guy's energy!
@itspaintosee
@itspaintosee 5 лет назад
Man I just started my first coding job. And I'm struggling. You've been such a great help though. Keep it up dude!
@bitcode_
@bitcode_ 6 лет назад
after struggling with this for 2 days, I got it with your video, thank you!
@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
@joeyh2541
@joeyh2541 4 года назад
Thanks for being so animated! I actually learned alot! :)
@rimshaarshad7834
@rimshaarshad7834 4 года назад
Best ever programming video :) no boring coding Just fun learning coding :P
@StarlightHeaven
@StarlightHeaven 6 лет назад
Great videos, great series and great teacher.
@ruthirlekar8632
@ruthirlekar8632 5 лет назад
Thank you !! You're Videos have really helped me.
@ziadtoufi5376
@ziadtoufi5376 2 года назад
Omg first time ive seen a teacher that good u get a sub rn
@atamoglannovruzov1189
@atamoglannovruzov1189 5 лет назад
you are just perfect ...thank you very much
@mo337
@mo337 3 года назад
You just got a new subscriber. Thank you a ton for simplifying it so much!
@MynhDaiK
@MynhDaiK 4 года назад
OMG this video appered when i was doing my function exercise
@codelyslearning
@codelyslearning Год назад
Thank you so much for this educational video, I learned so much.
@yuvalgal7057
@yuvalgal7057 5 лет назад
you are literally the best teacher i've ever seen, and im registered to Udemy,treehouse and pluralsight, Thank you !
@anthonyzornig
@anthonyzornig 2 года назад
Great style! Always a pleasure.
@juvenalgonzalez5291
@juvenalgonzalez5291 4 года назад
I like this guy, gonna look for more of your vids. Good content!
@bibhorkumar2281
@bibhorkumar2281 4 года назад
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...
@GoDXaviA
@GoDXaviA 6 лет назад
Great series :) i love it
@Forlorade
@Forlorade 5 лет назад
I love these and I love you.
@carlostho7403
@carlostho7403 2 года назад
This man is the best.
@mustafiz012
@mustafiz012 3 года назад
Thanks, pretty clean!
@GssUpp
@GssUpp Год назад
Thank you so much. You explaining everything so simple. Greetings from Germany!
@lajug2220
@lajug2220 6 лет назад
thank you so much, your videos very helpful :)
@riyaazct
@riyaazct Год назад
Such a great video.
@SACAS20
@SACAS20 4 года назад
Dudee! I understand so so the English but your explanation was really good, thanks
@mikepolo7661
@mikepolo7661 3 года назад
Unusual educational fromat, great job! Thanks for the videos, Daniel, very helpful!=)
@MontyKsycki
@MontyKsycki 6 лет назад
THANK YOU FOR SHARING!!!! :)
@NuhAleph
@NuhAleph 5 лет назад
You are THE best.
@thesmartest1919
@thesmartest1919 3 года назад
thank u so much it was so helpful
@arunkumar-mm7qs
@arunkumar-mm7qs 2 года назад
Awesome Teaching dude
@leamsi4ever
@leamsi4ever 5 лет назад
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!
@mo337
@mo337 3 года назад
Thank you so much
@phillipbarlow2011
@phillipbarlow2011 3 года назад
Great video, really helped me with my understanding of higher order functions, lost me at 8:45 though lol
@lycan2494
@lycan2494 5 лет назад
great video! ur very good at teaching :)
@dagmawitewodros5090
@dagmawitewodros5090 2 года назад
U got my subscription
@dbchrocker
@dbchrocker 3 года назад
Nice work 👍
@deepakbhargav7434
@deepakbhargav7434 4 года назад
THANK YOU SIR
@khiemgluong
@khiemgluong 3 года назад
I wish I could watch and understand all of your videos in a matter of minutes.
@A_Lesser_Man
@A_Lesser_Man 4 года назад
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.
@chadlew9593
@chadlew9593 3 года назад
thank youuu
@shivangchaturvedi237
@shivangchaturvedi237 4 года назад
Bravo!
@botleydot
@botleydot 3 года назад
Easy way to remove falsey values is `arr.filter(Boolean)`
@DaveCollison
@DaveCollison 3 года назад
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.
@MrMe-yu7ve
@MrMe-yu7ve 6 лет назад
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!
@charmainetabilas3132
@charmainetabilas3132 5 лет назад
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?
@DigitalMonsters
@DigitalMonsters 6 лет назад
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)
@reddwarfhead
@reddwarfhead 4 года назад
dude.. you're actually.. making sense.
@XpLoeRe
@XpLoeRe 2 года назад
.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!
@rocketsketch
@rocketsketch 6 лет назад
Hey what's your recording setup? Can you do a video on that? Your videos are entertaining as usual :)
@ga7853
@ga7853 6 лет назад
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'
@haciendadad
@haciendadad 5 лет назад
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.
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"
@rlasc84
@rlasc84 6 лет назад
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.
@unnamed49
@unnamed49 2 года назад
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+/);
@pratikkolge2490
@pratikkolge2490 6 лет назад
Zero is also falsy value. If the array contains zeroes they will be removed too..
@MrCk0212
@MrCk0212 3 года назад
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.
@beingian
@beingian 3 года назад
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.
@SruthiSNair
@SruthiSNair 3 года назад
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. 👍
@codewithpranavjeet
@codewithpranavjeet 4 года назад
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.
@Bomb4stic
@Bomb4stic 6 лет назад
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
@okoiful
@okoiful 6 лет назад
In FP you dont reassign a new value to a var.. you create a new one..its about the inmutability of data...
@vaibhavm1986
@vaibhavm1986 5 лет назад
X => X .... How did it bypass undefined?
@MeasuresDesperately
@MeasuresDesperately 4 года назад
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.
@filipkendes1866
@filipkendes1866 6 лет назад
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: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-HZ4D3wDRaec.html Also: sublime text: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-UCHzlUiDD10.html atom editor: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-d3OcFexe9Ik.html
@filipkendes1866
@filipkendes1866 6 лет назад
great job, That video helped me a lot. Love your effort
@MultiPerplexedDude
@MultiPerplexedDude 5 лет назад
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 :)
@jameskobe1716
@jameskobe1716 5 лет назад
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.
@teacherrussell5206
@teacherrussell5206 3 года назад
My favorite fish is now gefilter fish.
@malibaturhan
@malibaturhan 2 года назад
you can think like upper filter come with us and drainage goes
@ConsulthinkProgrammer
@ConsulthinkProgrammer 3 года назад
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 :)
@vishwakneelamegam9479
@vishwakneelamegam9479 3 года назад
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.
@nirajlakhadive
@nirajlakhadive 3 года назад
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
@hiteshsofat8458 4 года назад
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.
@cloroxbleach861
@cloroxbleach861 6 лет назад
hello
@brucelee7782
@brucelee7782 5 лет назад
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.
@halilualiyu6152
@halilualiyu6152 3 года назад
*I give all thanks to WAPTECS and twitter for helping me fix my Göogle account*
@sanukumar306
@sanukumar306 3 года назад
You get empty string because of that ending full stop symbol 😀
@azampasha6020
@azampasha6020 3 года назад
Ruj k shokha!
@chrisjoseph6491
@chrisjoseph6491 Год назад
ur a goat
@michaelrooze278
@michaelrooze278 3 года назад
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
@thedonsky5092
@thedonsky5092 3 года назад
the last part lost me with the /\W+/
@EricJost
@EricJost 6 лет назад
Hate those grimy arrays.
@sindygoro3800
@sindygoro3800 3 года назад
My account got disabled for nó reason, then a friend introduce me to WAPTECS who got my accóunt recovered successfully,🤗
@josebarona271
@josebarona271 5 лет назад
I want u to be my dad
@DavidIFernandezMunoz
@DavidIFernandezMunoz 3 года назад
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.
Далее
16.3: ES6 Arrow Function - Topics of JavaScript/ES6
22:32
Беда приходит внезапно 😂
00:25
Просмотров 238 тыс.
Впервые дал другу машину…
00:57
JavaScript Function - What's your Function?
12:27
Просмотров 180 тыс.
What do programmers actually do?
9:20
Просмотров 2 млн
WHY IS THE STACK SO FAST?
13:46
Просмотров 140 тыс.
16.1: let vs var - Topics of JavaScript/ES6
12:20
Просмотров 222 тыс.
16.2: const - Topics of JavaScript/ES6
7:42
Просмотров 74 тыс.
JavaScript Array filter method
9:15
Просмотров 18 тыс.