DEV Community

Cover image for LeetCode 2634. Filter Elements from Array (Easy)
Julia πŸ‘©πŸ»β€πŸ’» GDE
Julia πŸ‘©πŸ»β€πŸ’» GDE

Posted on • Updated on

LeetCode 2634. Filter Elements from Array (Easy)

A few weeks ago, I started solving problems at LeetCode. Even though I've been in tech for three years, I hardly ever code in JavaScript because my position as an accessibility specialist doesn't really involve that programming language.

But my brain likes to challenge itself, so I practise JavaScript in my spare time. So if you're currently doing the same, let's share our approaches and learn together. πŸ€“

Starting point

Given an integer array arr and a filtering function fn, return a filtered array filteredArr.

The fn function takes one or two arguments:

  • arr[i] - number from the arr
  • i - index of arr[i]

filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true.

‼️ Please solve it without the built-in Array.filter method.

My Submission

Let's take a look at my code. Yours maybe looks different, and that's okay. Everyone has their own approach.

var filter = function(arr, fn) {
    const filteredArr = [];

    for(let i = 0; i < arr.length; i++) {
        if (fn(arr[i], i)) {
            filteredArr.push(arr[i])
        } 
    }
    return filteredArr;
};
Enter fullscreen mode Exit fullscreen mode

What happens here?

var filter = function(arr, fn) {
    ...
}
Enter fullscreen mode Exit fullscreen mode

What was given by LeetCode was the outer declaration*, the initialization of var filter, which was assigned a function that takes two arguments, an array of numbers arr and a filter function fn.

πŸ‘» Note: I personally never use var when declaring a variable, I always opt for let or const, but since this was the default, I'll keep it that way (there's nothing really wrong with using var).

const filteredArr = [];
Enter fullscreen mode Exit fullscreen mode

I declare an empty array filteredArr which will store the filtered elements.

for(let i = 0; i < arr.length; i++) {
    ...
}
Enter fullscreen mode Exit fullscreen mode

Since we are not allowed to use the Array.filter method, I am using a for loop to go over the given array arr. We start the for loop by setting kind of a counter by initializing a variable let i and set it to 0.
The second part of the loop is to compare the value of i against the length of the array arr.length. The loop should only run as long as i is smaller array (so, as long it is true).
After checking, if i is still smaller, i will be increased by 1 through i++ and the function inside the loop will be called as long as this is the case.

if (fn(arr[i], i)) {
   filteredArr.push(arr[i])
}
Enter fullscreen mode Exit fullscreen mode

Inside the loop is an if statement. The if statement contains the given function fn which can take two arguments, the number in the array arr[i] and the index of the number i.
The function iterates over the arr (as long as the for loop is true) and compares the number with the value given by the function against its expression.

So in case the expression says: is the number inside the array greater then ten arr[i] > 10; and the number is 20, then it would return true. And when it is true, we push the number to the new created array filteredArr using the push() method.

return filteredArr;
Enter fullscreen mode Exit fullscreen mode

Last thing for us to do is to return the filteredArr. That's it 😎.

What was it like for you to solve this problem? Was everything clear from the start or did you have difficulty understanding something?

I can imagine it always takes a bit of getting used to thinking back to the origin when you are used to using array methods.


*I'm not happy with what I'm calling it. Do you have any ideas on how I could describe it better?
In general, I am bad at explaining technical stuff. So any advice is welcome to improve my explanation skills πŸ™πŸ½.

Top comments (6)

Collapse
 
kaamkiya profile image
Kaamkiya

I think you can also do something like this:

var filter = function(arr, fn) {
  return arr.filter(i => fn(i));
}
Enter fullscreen mode Exit fullscreen mode

Array.prototype.filter is a function that returns a new array of items if it's callback returns true.

That probably needs clarification, so here's an example:

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

// the callback for arr.filter is the function we pass to it
// this callback returns true when the number is even
// if the callback returns false, the number is removed
arr = arr.filter(num => num % 2 === 0);

console.log(arr); // ==> [0, 2, 4, 6, 8];
Enter fullscreen mode Exit fullscreen mode

Your solution works well too though! I hope you learned something new :)

Collapse
 
yuridevat profile image
Julia πŸ‘©πŸ»β€πŸ’» GDE

Thanks for your suggestion. :)

As mentioned in the description it should be solved without the filter method.

I am grateful for your explanation, I am sure others will learn a lot from it.

Collapse
 
kaamkiya profile image
Kaamkiya

Oh, I hadn't read the description. Now your solution makes more sense :)

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

I'm not happy with what I'm calling it. Do you have any ideas on how I could describe it better?

How about this?

  1. The art of filtering in JavaScript arrays :D

  2. A practical approach to filtering in JavaScript. Let's learn together!

I'm not a fan of Leetcode, by the way. Did solve around 120 questions though :D

Collapse
 
yuridevat profile image
Julia πŸ‘©πŸ»β€πŸ’» GDE

Hey @anmolbaranwal thank you for your response 😊
I am not quite sure how your suggestions fit instead of outer declaration* Or did I misunderstand something? πŸ™Š

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

I thought you were referring to the title; that's why I proposed some alternative ones. Sorry for any confusion, I guess I misunderstood :D