DEV Community

Cover image for LeetCode 2634. Filter Elements from Array (Easy)

LeetCode 2634. Filter Elements from Array (Easy)

Julia 👩🏻‍💻 GDE on February 04, 2024

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