How recreate javascript array method without filter(), sort(), map() and reduce() ?
Tags: webdev, javascript, programming, tutorial
Published: 2023-03-01 07:30:00

JavaScript's built-in array methods such as filter(), sort(), and map() are incredibly useful for working with arrays, but there may be situations where you can't use them. For example, you may be working in an environment that doesn't support these methods, or you may need to optimize your code for performance reasons. In these cases, it's important to know how to recreate these methods without using them.

First, let's take a look at the **filter()** method. The filter() method is used to create a new array with all elements that pass a certain test. One way to recreate this method without using it is to use a for loop and a temporary array to store the filtered elements. Here is an example:

```javascript
function customFilter(arr, callback) {
  let filtered = [];
  for (let i = 0; i < arr.length; i++) {
    if (callback(arr[i], i, arr)) {
      filtered.push(arr[i]);
    }
  }
  return filtered;
}
```
This function takes in an array and a callback function as arguments. The callback function is used to test each element in the array. If an element passes the test, it is added to the filtered array.

Here's an example usage of the customFilter function:

```javascript
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = customFilter(numbers, (num) {
  return num % 2 === 0;
});
console.log(evenNumbers); // [2, 4]
```
In this example, the customFilter function is called with numbers as the first argument and an anonymous callback function as the second argument. The anonymous function checks if each number is even by checking if the remainder when divided by 2 is equal to 0. The customFilter function returns a new array evenNumbers containing only the even numbers from numbers.

Next, let's take a look at the **sort()** method. The sort() method is used to sort the elements of an array in ascending or descending order. One way to recreate this method without using it is to use a nested for loop and an if statement. Here is an example:

```javascript
function compareFn(a, b) {
  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
  return 0;
}

function customSort(arr, compareFn) {
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (compareFn(arr[i], arr[j]) > 0) {
                let temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}
```
This function takes in an array and a compareFn function as argument, the compareFn function is used to compare two elements of the array and determine their relative order.

Finally, let's take a look at the **map()** method. The map() method is used to create a new array with the results of calling a provided function on every element in the original array. One way to recreate this method without using it is to use a for loop and a temporary array to store the mapped elements.

```javascript
function customMap(arr, callback) {
  let mapped = [];
  for (let i = 0; i < arr.length; i++) {
    mapped.push(callback(arr[i], i, arr));
  }
  return mapped;
}
```
This function takes in an array and a callback function as arguments. The callback function is called on each element of the array and the result is added to the mapped array.

The Array method **reduce()** allows you to iterate over an array and apply a callback function to each element, accumulating the results in a single value. Here is an example of how you can recreate the `reduce()` method without using `reduce()`:

```javascript
function myReduce(arr, callback, initialValue) {
  let accumulator = initialValue;
  for (let i = 0; i < arr.length; i++) {
    if (accumulator === undefined) {
      accumulator = arr[i];
    } else {
      accumulator = callback(accumulator, arr[i], i, arr);
    }
  }
  return accumulator;
}
```
This function takes in an array `arr`, a callback function `callback`, and an optional initial value for the accumulator. It uses a for loop to iterate over the array, and for each element, it applies the callback function to the accumulator and the current element. If the initial value for the accumulator is not provided, the first element of the array is used as the initial value. The callback function is called with four arguments: the accumulator, the current element, the current index and the array.

Here's an example of how you can use the `myReduce()` function to add up the values of an array like the `reduce()` method:

```javascript
let numbers = [1, 2, 3, 4];
let sum = myReduce(numbers, (acc, curr) => acc + curr);
console.log(sum) // 10
```
Note that, this function will not work with arrays that are not fully dense (arrays that have `undefined` values between the defined values)

That's correct, the `myReduce()` function I provided uses a for loop to iterate over the array, which will skip over any `undefined` values in the array. If you need to support arrays with non-dense values, you will need to use a different iteration method, such as `for...of` or `while` loop, to iterate over the array, or use Array.prototype.filter() to filter out the undefined values before running the loop.

---

In conclusion, recreating JavaScript's array methods such as filter(), sort(), and map() without using them is not difficult. By using for loops and temporary arrays, you can recreate these methods in a way that is compatible with any environment and can also be optimized for performance. It's always a good practice to know the underlying mechanism of those array methods, this will make you a more confident developer, who can decide which method is the most appropriate for his use case.