5

Understand JavaScript Array Methods By Implementing Them

 1 year ago
source link: https://dev.to/biraj21/javascript-array-methods-understand-by-implementing-54g3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for Understand JavaScript Array Methods By Implementing Them
Biraj

Posted on Jan 20

• Updated on Jan 24

Understand JavaScript Array Methods By Implementing Them

When I started learning modern JavaScript (or ES6 😏), array methods were one of the most challenging things for me to wrap my head around. I had no idea what to do with these maps, filters, reduce & stuff. And now that I understand them, I believe that the best way to understand them properly would be to try to implement them on our own.

To understand this post, you'll need an understanding of for loops, arrays (duh), functions (also arrow functions), callbacks & ability to interpret code 🌝. You should be able to read the example code & understand what each method does under the hood. Btw if you don't know what callbacks are, here's my explanation.

Callback Functions (a crash course)

A callback function is just a function that is passed as an argument to another function, and this callback function will be then called back (callback get it? 🤯) internally when it's needed.

function cb() {
  console.log("this is my callback function...");
}

function someStuff(cb) {
  // doing some stuff...
  console.log("done with it...");
  // maybe doing some more stuff...
  cb();
  // again doing something...
}

someStuff(cb);
Output:
done with it...
this is my callback function...

Or you can write it like:

someStuff(() => {
  console.log("this is my callback function...");
});

someStuff(function () {
  console.log("this is my callback function...");
});

All three of these ways are equivalent & will produce the same output. What's ultimately happening is that you are just passing a function as an argument, and it's being called internally when it's needed. That's it.

Now coming to array methods, this is how I want you to think about them:

  • An array method will take a callback function.
  • Now internally, this method will create a new array.
  • Then it will 'run a for loop' & iterate over each element of this array.
  • For each iteration, the current element will be passed as an argument to the callback function, which will then do something with that value.
  • Then the value that is returned by the callback function is used by the method in some way to add the current new value to the resultant array. (specifics differ for each method)
  • After it's done with all the elements, it will return the new array.

Notes:

  1. Most of the array methods will not change the original array & will return an entirely new array.
  2. This was just a general & informal way to understand the process.
  3. The callback function will also get the index of current element as its second argument.

Now let's look at some example implementations 🚀. Btw each example will have these:

  1. Me blabbering something 🤡
  2. Implementation code 🧑‍💻
  3. Output 💻
  4. Code's explanation 🧠

Example 1: map() method

The JavaScript map method 'transforms' an array to into an new array by calling a callback function on each element, and populating the resultant array with it's return value. The reason I enclosed 'transforms' in quotes because it does not actually modify the original value.

function map(arr, callback) {
  const result = [];
  for (let i = 0; i < arr.length; ++i) {
    result.push(callback(arr[i], i));
  }

  return result;
}

const numbers = [2, 4, 9, 10];
const squares1 = numbers.map((num) => num ** 2);
const squares2 = map(numbers, (num) => num ** 2);

console.log(squares1);
console.log(squares2);
Output:
[ 4, 16, 81, 100 ]
[ 4, 16, 81, 100 ]
Explanation:
result = [] (initially)

 2 ** 2 =   4 [4]
 4 ** 2 =  16 [4, 16]
 9 ** 2 =  81 [4, 16, 81]
10 ** 2 = 100 [4, 16, 81, 100]

returns [4, 16, 81, 100]

Example 2: filter() method

The filter method is essentially used to filter out some elements based on some test. The callback function for filter should return a boolean, which will be used to determine which elements will be there in the resultant array. If the callback return true for the current element, only then it will be added to the resultant array.

function filter(arr, callback) {
  const result = [];
  for (let i = 0; i < arr.length; ++i) {
    if (callback(arr[i], i)) {
      result.push(arr[i]);
    }
  }

  return result;
}

const numbers = [0, -1, 4, -10, 5, 10, 100, -22];
const negatives1 = numbers.filter((num) => num < 0);
const negatives2 = filter(numbers, (num) => num < 0);

console.log(negatives1);
console.log(negatives1);
Output:
[ -1, -10, -22 ]
[ -1, -10, -22 ]
Explanation:
result = [] (initially)

  0 < 0 = ❌ []
 -1 < 0 = ✅ [-1]
  4 < 0 = ❌ [-1]
-10 < 0 = ✅ [-1, -10]
  5 < 0 = ❌ [-1, -10]
 10 < 0 = ❌ [-1, -10]
100 < 0 = ❌ [-1, -10]
-22 < 0 = ✅ [-1, -10, -22]

returns [-1, -10, -22]

Example 3: reduce() method

The reduce method is used to perform some operation on the array & somehow 'reduce it' to a single value. Basically just take an array, do something on it & just return a single value. The callback for this method would take 2 arguments: accumulator & current value. The current value argument is the same old element at current index, but what is this accumulator though?

What is accumulator?

The accumulator is just a variable which is given some initial value (or it would set to the first element in the array by default) which then stores (or accumulates 🌝) the value that is returned by the callback. Finally, this value is then returned by reduce(). The most common example for this would be to calculate the sum of all the elements in an array, and I think that reading the code would be better than reading my words.

function reduce(arr, callback, initialValue) {
  let accumulator = initialValue;
  let start = 0;
  if (arguments.length !== 3) {
    accumulator = arr[0];
    start = 1;
  }

  for (let i = start; i < arr.length; ++i) {
    accumulator = callback(accumulator, arr[i], i);
  }

  return accumulator;
}

const numbers = [-1, 5, 2, -3, 10];
const sum1 = numbers.reduce((a, c) => a + c, 10);
const sum2 = reduce(numbers, (a, c) => a + c, 10);

console.log(sum1);
console.log(sum2);
Output:
23
23
Explanation:
  • Here the initial value of the accumulator would be 10.
  • Now here's what's gonna happen (I'm gonna refer to accumulator as acc:
acc = 10 (initially)

acc = 10 + -1 =  9
acc =  9 +  5 = 14
acc = 14 +  2 = 16
acc = 16 + -3 = 13
acc = 13 + 10 = 23

returns 23
  • Btw if we hadn't provided the initial value to reduce(), then it would've been:
acc = -1 (default: first element of the array)

acc = -1 +  5 =  4
acc =  4 +  2 =  6
acc =  6 + -3 =  3
acc =  3 + 10 = 13

returns 13

You can read more about JavaScript Array at MDN. Thank you for reading my post. Your honest feedback (if any) is appreciated 🤝.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK