const - JS | lectureWorking With Arrays

The filter Method

Working With Arrays

Now let's learn about the filter Method. Which, as we learned before, is used to filter for elements that satisfy a certain condition. And how do we specify such a condition? Well, you guessed it, we use a callback function again.

Let's again consider our movements array.

script.js
const movements = [300, 600, -800, 7000, -750, -150, 90, 1500];

Just like the map method, the syntax is the same, and the callback function also gets access to the current array element, the index, and the entire array. But we will only work with the current element in this lecture.

script.js
movements.filter(function (movement, index, movements) {
  // do something...
});

Let's start by creating an array of deposits. Deposits refer to movements that are greater than 0. That is, we want to filter out all the negative values in the movements array. Hence the condition is simply movement > 0.

script.js
const deposits = movements.filter(function (movement) {
  return movement > 0;
});

As you can see, the callback function returns a boolean value. In other words, the callback functions returns a value that coerces to true to include the current element in the new array, and false to exclude it. Hence, only the array elements, for which the condition is true will make it into the deposits array. All the other elements will be filtered out.

script.js
console.log(deposits); // [300, 600, 7000, 90, 1500]

Let's implement the same thing using the for-of loop so that you can appreciate the difference.

script.js
const deposits = [];
for (let movement of movements) {
  if (movement > 0) {
    deposits.push(movement);
  }
}

console.log(deposits); // [300, 600, 7000, 90, 1500]

Alright! You might now ask, what's the difference between the two approaches? Why not just use the for loop for everything? And the reason for that is, again, the push that exists in JavaScript for using more functional code.

script.js
movements.filter((movement) => {
  /* do something... */
});

movements.map((movement) => {
  /* do something... */
});

But there's also a more practical implication here. And that's because we can chain array methods together to build a big final result. A bit similar to what we did in the previous lecture when computing user names.

script.js
user
  .toLowerCase()
  .split(' ')
  .map((word) => word[0])
  .join('');

But here, we are mixing string and array methods. Later on, we will do method chaining only with array methods, which would be impossible using the for loop. So that's another big advantage of using methods instead of the regular for loop.

To finish this lecture, as a small challenge, try to create a new array containing the withdrawals only. Once you are done, you can move on to the next lecture where we will learn about the reduce method.