Filter Elements from Array (Transforms) - Leetcode 2634 - JavaScript 30-Day Challenge

NeetCodeIO · Beginner ·⚡ Algorithms & Data Structures ·3y ago

Key Takeaways

The video demonstrates solving Leetcode's 30-day JavaScript challenge, specifically day 5, using JavaScript's built-in filter method and a custom implementation of the filter method without using the built-in filter method, showcasing the difference between declarative and imperative programming approaches.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem filter elements from array I believe this is day five of the JavaScript challenge it's a pretty similar problem to yesterday we're given an array it's a pretty similar problem to yesterday but I'm going to go through a couple important details about JavaScript as a language just because we have the time we're given an integer array and a filtering function and we want to return a new array with fewer or equal number of elements if you're not familiar with filtering functions this last sentence might confuse you what do they mean by a new array with fewer or equal number of elements well think about what filtering is going to do take a look at this example down here we have an array with four elements 0 10 20 and 30. we have a filter function that checks if a value is greater than 10 if it's greater than 10 it looks like we're returning true if it's not greater than 10 we are returning false so as you might guess this function is going to look at each element and determine if it's greater than 10 and for the ones that are greater than 10 we're going to create a new array with those elements 0 is not greater than 10 neither is 10 but 20 and 30 are so that's what we get in the output so that kind of satisfies the requirement of fewer or equal number of elements that's kind of what filtering does by definition and in terms of coding it up on the right over here all we have to do is just take this array every array has a method just like every array has a method map which can take each value and map it to a new value it also has the method filter where it will do exactly what we talked about earlier now it has to be provided some function because how exactly are we going to filter these like what exactly is the criteria if we wanted to recreate the greater than 10 function that we were given in example one we could do so with a Lambda function or an inline Anonymous function like this where the parameter is going to be just like they told us over here the array value and the index so here I'm going to just create a couple variables for those I'm going to call it n and I'm going to call the second one I N is going to be the value I is going to be the index we don't have to pass these in remember we're just creating a function here that we're passing into the filter function and then this function will be called underneath the hood this is kind of an example of declarative programming because we are not explicitly writing this out this is a sort of functional programming if we were to do it the opposite way where which I'm going to do later on that is going to be an example of imperative programming and I'll show you that in just a second but for now let's finish up this function how do we decide what to return well to create a function let's create our curly braces and then Define the function just kind of like they did over here I'm just going to go ahead and copy that return n is greater than 10. so this will obviously not pass the problem because we're not doing what they told us to do because it's pretty much a trivial problem to solve but this is an example of filtering and if you want to get even more fancy you can get rid of these braces these curly braces and get rid of the return statement because this Anonymous function is just a single liner and it's returning the value anyway let's get rid of the semicolon as well and this is equivalent to the previous code that we had but now let's actually solve the problem I'm going to instead of passing in the function we defined I'm going to pass an FN the function they passed into us and I'm going to return this and then run it to make sure that it works and as you can see yes it does the only problem is they told us we're not allowed to use a built-in filter method so let's solve this the imperative programming way where we actually explicitly write out the steps we manage our own state so I'm going to first build the new output array well initially it's going to be an empty array result and then I'm going to go through every single element n in the input array but remember in is not the key word you use to access the value of a data structure whether it's a object or an array if we want the values we use the keyword of now with each of these values we just want to apply the filter and then decide whether we should add it to the result or not so easiest way to do that is with an if statement right let's call FN on the N value as well as the index but then we realize we actually don't have the index so we remember to get the index from an array we actually do have to use the keyword in so good that we are reviewing these Concepts so now I'm going to change this to I because it's the index so now we can pass the index in but how do we get the actual value n well we can do that by array at index I and we reviewed last time that this is actually a string when you iterate through it like this so we can cast it to a number and then we can finish up our if statement here if this evaluates to true then then we want to our result push the value array at index I and then after that we just need to return our result I'm going to comment this out and then run the below code to prove that it works and as you can see yes it does but it is quite a bit slower that's mostly I think because we are creating a new Dynamic array and potentially resizing it many many times array filter will actually update the array in place but we are not allowed to do that so we can go with this approach very quickly I think it's also worth mentioning that we could and probably should iterate through this just with a pointer index I because having to convert a string to a number can be error prone and you might not remember to do that it can cause bugs sometimes so usually it's better to actually iterate through arrays like this array dot length and then I plus plus so this syntax is pretty similar to most languages except of course python so what we're doing here is declaring a variable with the let keyword we can't use the const keyword because we are going to have to increment this pointer I so I'm going to use the let keyword and we're going to keep going until we're in bounds of the array and increment on each iteration of the loop so initially we start at index 0 and we do not have to convert this to a number now though I think it would technically work if we did but let's run this code now and see if it works and as you can see yes it does now lastly I want to take a couple minutes to quickly skim through the editorial because I think there are a couple nuggets of knowledge in here that we didn't really have to learn about in the problem which kind of makes me wonder why they include this in the editorial but oh well one is that JavaScript has this concept of truthy and falsy values and many languages do including python the idea is that when you write if statements we know that the statement is evaluated based on whether it is a true or whether it is a false but actually non-boolean values such as integers like zero can all also be used in if statements what would this execute this would be false zero is false what about an empty string well usually that's false if we were doing this in Python we would also get the same result and they list a bunch of other things that are considered falsy which one is the false value itself the number zero the number negative zero not a number which usually happens when you try to divide by zero an empty string a null value and the undefined value undefined is a bit special in JavaScript most languages don't really have this concept the idea is that when I declare a variable such as const n is going to initially be equal to null n is explicitly set to null but what happens if I actually don't set n to anything what's this going to be it's going to be undefined because we never assigned it that's the distinction between null and undefined null you have to be explicit about but undefined is pretty much always going to be there you can't really avoid running into undefined values in JavaScript even in typescript you sometimes can't avoid that now they do mention here that sometimes it can be dangerous like this if statement over here if user input isn't null and it isn't an empty string then do some operation which can be shortened to this statement below but that could be dangerous because what if user input is the value zero up here like the integer zero then what would happen then this if statement would not execute but do we want it to execute perhaps we do in that case it's worth being explicit like this it's worth being explicit to check if a value is actually not equal to null maybe we are allowed to use zero we're just not allowed to use null or an empty string sometimes you find me writing stuff out like this in leak code problems just because I don't want to confuse myself there's also this concept in JavaScript that the conditional operators can actually be used for assignment what this is doing here is if the text input variable evaluates to false then the string value will be assigned to what comes after the or conditional here in many languages this is not the case I don't believe this would happen in Java or C plus plus you would probably get a type error because you're not allowed to use a string in a or condition but in Python this actually does work just to quickly prove it to you I'm going to write rent false or some string like hello so what will happen with this will this print false will this print true because shouldn't this evaluate to a truthy value so technically this condition should evaluate to true but actually it doesn't as you're about to see when I run this code we actually get an output of hello because the first part of the condition evaluates to false so the rest of the condition is what is actually returned here so we could even assign sign this to a variable over here in Python let's say just n for no reason and then when we print the end value we'll kind of get the same thing we'll get hello but now if I try to use that same n value in a conditional down here and then try to print something maybe I'm going to print world now you'll see that this time the N value is going to do something different the N value here evaluates to true because even though the value here is assigned to a string in the presence of an if this will turn into a conditional true or false a Boolean value actually so I know this is python but actually JavaScript operates the same way I just wanted to show you a different language and another thing that's worth knowing is the nullish coalescing operator in JavaScript this is pretty handy dandy in many cases because it operates similarly to this thing over here where if this part evaluates the false everything else is what's returned so down on the right right over here if I do an assignment n is going to be equal to some empty string but if that empty string is falsy then do everything after then assign it to what comes after the string which might be hello so if this evaluates to false then the double question mark will execute the rest of this part of the code and then assign it to this variable so that's just kind of a shorthand way of maybe even writing out a ternary operator like this would be equivalent to if I wrote down here const n is equal to empty string but if that is equal to empty string if empty string is true otherwise we are going to assign this to hello I believe these two lines of code are equivalent if this is true it'll be assigned to n if it's not it'll be assigned to hello now skimming through the rest of this article I don't believe there's anything crazy that we haven't talked about yet I think the rest of these Solutions we covered last time so I will close things off by mentioning that JavaScript is a weekly typed language they mentioned that also in this editorial but I'm sure they're going to talk about it more in the future JavaScript challenges so that's where I will leave things but python if you're familiar with it is not quite a weekly type language it's sort of a strongly typed language though it's not like the strongest but this is just a bit of food for thought if you're interested in researching something else I'll probably cover these Concepts in future videos if you're interested so definitely subscribe if you want more thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews Solving day 5 of leetcode's 30-day javascript challenge. Today we learn a bit about the the difference between declarative and imperative programming. 🥷 Discord: https://discord.gg/ddjKRXPqtk 🐦 Twitter: https://twitter.com/neetcode1 🐮 Support the channel: https://www.patreon.com/NEETcode ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf 💡 DYNAMIC PROGRAMMING PLAYLIST: https://www.youtube.com/watch?v=73r3KWiEvyk&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=1 Problem Link: https://leetcode.com/problems/filter-elements-from-array/ 0:00 - Read the problem 1:20 - Declarative Programming Solution 3:35 - Imperative Programming Solution 6:22 - Reading the Editorial 9:25 - Similarities with Python 10:40 - Finishing Editorial leetcode 2634 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

This video teaches how to filter elements from an array using JavaScript's built-in filter method and a custom implementation, highlighting the differences between declarative and imperative programming. It also covers JavaScript fundamentals such as falsy values, conditional operators, and weakly typed languages.

Key Takeaways
  1. Explicitly write out the steps to filter elements from an array using imperative programming
  2. Define a filtering function using a lambda function or an inline anonymous function
  3. Use JavaScript's built-in filter method to filter elements from an array
  4. Pass an FN function into the code
  5. Build a new output array
  6. Go through every single element in the input array
  7. Apply the filter and decide whether to add the value to the result
  8. Cast the index to a number when getting the actual value from the array
💡 The video showcases the importance of understanding the difference between declarative and imperative programming approaches in JavaScript, as well as the use of falsy values, conditional operators, and weakly typed languages.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (6)

Read the problem
1:20 Declarative Programming Solution
3:35 Imperative Programming Solution
6:22 Reading the Editorial
9:25 Similarities with Python
10:40 Finishing Editorial
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →