JavaScript Array Methods: Using map, filter, and reduce

Title: JavaScript Array Methods: Using map, filter, and reduce

In this comprehensive tutorial, we will explore the powerful and widely-used array methods in JavaScript: map(), filter(), and reduce(). These methods are essential tools for developers, enabling efficient manipulation and transformation of arrays in a clean and readable manner. Whether you are a student, a beginner, or someone looking to enhance their JavaScript skills, this guide is tailored to help you understand these fundamental methods thoroughly.

The primary objective of this article is to provide clear, beginner-friendly explanations of how these methods work, complete with practical examples to illustrate their usage. By the end of this tutorial, you’ll not only grasp the theory behind these array methods but also gain the confidence to incorporate them into your own JavaScript projects, enhancing both productivity and code quality.

What is Array?

In JavaScript, a data structure called an array is used to hold several values in a single variable. Each entry in this ordered collection can be accessed by its index, which starts at zero.

map() Method

An effective aspect of JavaScript's Array prototype is the map() method, which enables programmers to construct a new array filled with the outcomes of applying a specified callback function to each element of the original array. This technique preserves immutability and is very helpful when you need to change or transform data in an array without affecting the original array.

For instance, in our JavaScript we would like to output each value of an array variable. Commonly, we use for() loop to iterate each value to output like the following:

  1. // Sample Array
  2. let sample_array = ["Array 101", "Array 102", "Array 103", "Array 104"]
  3.  
  4. // Using For Loop
  5. for(var i = 0; i < sample_array.length; i++){
  6.     console.log( sample_array[i] );
  7. }

Instead of using the for() loop, consider utilizing the map() method, which can produce the same desired result efficiently. See the following example:

  1. // Sample Array
  2. let sample_array = ["Array 101", "Array 102", "Array 103", "Array 104"]
  3.  
  4. // Using Map Method
  5. sample_array.map(function(val){
  6.     console.log( val );
  7. })

Result:

JavaScript Array Methods: Using map, filter, and reduce

Or,

  1. // Sample Array
  2. let sample_array = ["Array 101", "Array 102", "Array 103", "Array 104"]
  3.  
  4. // Using Map Method w/ key
  5. sample_array.map(function(val, key){
  6.     console.log( `${key} => ${val}` );
  7. })

JavaScript Array Methods: Using map, filter, and reduce

filter() Method

The filter() method is an essential tool in JavaScript for creating a new array that consists of only the elements from the original array that meet specific criteria. This method is a part of the Array prototype and helps developers efficiently filter data based on conditions without altering the original array, ensuring data immutability.

Each element in the calling array is iterated over by the filter() method, which then applies a callback function that is supplied and returns a boolean value. The current element is added to the new array if the callback returns true. The element is excluded if it returns false. A new array containing just the elements that pass the test specified by the callback function is the end result.

In instance, we would like get only some of the items in array. In this scenario we can also use the for() loop function to achieve this.

Result:

  1. const array_data = [-100, 100, -200, 200, -300, 300]
  2.  
  3. // Using For Loop
  4. var result = [];
  5. for (var i = 0; i < array_data.length; i++)
  6. {
  7.     if(array_data[i] >= 0){
  8.         result.push(array_data[i]);
  9.     }
  10. }
  11.  
  12. console.log(result)

JavaScript Array Methods: Using map, filter, and reduce

Rather than using that approach, you can leverage the filter() method to achieve the same result in a simpler and more efficient manner. Check out the example below:

Result:

  1. const array_data = [-100, 100, -200, 200, -300, 300]
  2.  
  3. // Using Filter Method
  4. var result = array_data.filter((val) => val >= 0);
  5.  
  6. console.log(result)

JavaScript Array Methods: Using map, filter, and reduce

reduce() Method

The reduce() method is a highly powerful and flexible array method in JavaScript. It enables you to apply a user-defined "reducer" callback function to each element in an array, processing them sequentially and accumulating a final result. One of the key benefits of reduce() is its ability to take an array and return a single output, which could be a number, string, object, or any other data type. This makes it an indispensable tool for various tasks, including summing values, modifying arrays, or merging multiple elements into a unified structure.

This method accepts two parameters: the first is the callback function, which is executed on each element of the array. The second is the initial value for the accumulator, a variable that keeps track of the accumulated result throughout the computation. Providing an initial value is optional in this method.

For instance, we would like sum all the array item values. To achieve this we can also use the for() loop function to iterate the items.

  1. // Sample Array Data
  2. var prices = [200.84, 100.03, 70.49, 80.83, 23.48]
  3.  
  4.  
  5. // Using For Loop
  6. var total = 0;
  7. for (var i = 0; i < prices.length; i++) {
  8.     total += prices[i];
  9. }
  10. console.log(total)

Instead of using the for() loop, we can utilize the reduce() method to achieve the same result in a simpler and more efficient way.

  1. // Sample Array Data
  2. var prices = [200.84, 100.03, 70.49, 80.83, 23.48]
  3.  
  4. // Using Reduce Method
  5. var total = prices.reduce((previous_price, current_price) => previous_price + current_price, 0)
  6. console.log(total)

JavaScript Array Methods: Using map, filter, and reduce

There you have it! I hope this JavaScript map, filter, and reduce method tutorial will help you with what you are looking for and for your future projects.

Explore more on this website for more Tutorial, Free Source Code, and Articles covering various programming languages.

Happy Coding :)

Add new comment