Filter Elements from Array | #2634 | LeetCode Solution

Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode

Problem : Filter Elements from Array | #2634 | LeetCode

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.


Example 1:

Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }

Output: [20,30]

Explanation:

const newArray = filter(arr, fn); // [20, 30]

The function filters out values that are not greater than 10

Example 2:

Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }

Output: [1]

Explanation:

fn can also accept the index of each element

In this case, the function removes elements not at index 0

Example 3:

Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }

Output: [-2,0,1,2]

Explanation:

Falsey values such as 0 should be filtered out


Solution:

            /**

     * @param {number[]} arr

     * @param {Function} fn

     * @return {number[]}

     */

    var filter = function (arr, fn) {


        filteredArr = []

        for (let i = 0; i < arr.length; i++) {

            if (fn(arr[i], i)) {

                filteredArr.push(arr[i])

            }

        }

        return filteredArr


    };



Explanation:

Certainly, let's break down the code step by step:


1. The code defines a function called `filter` which takes two parameters:

   - `arr`: An array of numbers.

   - `fn`: A function that will be used as a filter criteria.


2. Inside the `filter` function, a new array called `filteredArr` is declared. This array will be used to store the elements of the input array `arr` that satisfy the filter condition defined by the `fn` function.


3. The function then enters a `for` loop that iterates through each element of the input array `arr`. The loop is controlled by the variable `i`, which starts at 0 and goes up to the length of the array.


4. Inside the loop, there's an `if` statement that checks whether the result of calling the `fn` function with the current element of `arr` and its index `i` is truthy.


   - `fn(arr[i], i)`: This calls the `fn` function with two arguments: the current element `arr[i]` and its index `i`. The purpose is to allow the `fn` function to evaluate the element and index and return `true` or `false` based on some condition.


5. If the result of `fn(arr[i], i)` is `true`, indicating that the element meets the filter criteria defined by `fn`, then that element is pushed into the `filteredArr` using `filteredArr.push(arr[i])`.


6. After the loop has processed all elements in the input array `arr`, the `filteredArr` now contains the elements that passed the filter.


7. Finally, the `filteredArr` is returned as the result of the `filter` function.


In summary, this `filter` function takes an array and a filter function as input, and it iterates through the array, applying the filter function to each element. It collects the elements that satisfy the filter criteria into a new array and returns that filtered array as the output. This is essentially an implementation of a basic filtering operation similar to JavaScript's built-in `Array.prototype.filter` method.





Related Blogs
Generate Fibonacci Sequence - JavaScript | Hackerank
Author: neptune | 07th-Apr-2023
#JavaScript #Hackerrank
Write a JavaScript function fibonacciSequence() to generate a FIbonacci sequence...

To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

Array Reduce Transformation | #2626 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array...

Add Two Promises | #2723 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
Given two promises `promise1` and `promise2`, return a new `promise`. `promise1` and `promise2` will both resolve with a number...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
#JavaScript
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
#JavaScript
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?
Author: neptune | 31st-Jul-2024
#JavaScript #API
Building a blogging website using React, Node.js, and Jamstack architecture was a rewarding experience...

How to Perform Unit Testing in React Components with Examples?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
Unit testing in React is an essential practice to ensure the reliability and robustness of your components...

Do you know ! How to manage State in Functional & Class Components in React ?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
State management in React has evolved significantly with the introduction of Hooks...

Why, What, and When: Understanding Jamstack?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Jamstack represents a modern approach to web development that addresses many of the challenges faced by traditional architectures...

How to Get Started with Jamstack: A Comprehensive Guide?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Getting started with Jamstack involves choosing the right tools, setting up a structured development environment...

View More