Methods for Transformation

Array Methods

Methods for Transformation

🙋 Need help? Ask an expert now!

The array methods for transformation are also advanced methods that you do not need to memorize. The filter() and map() method returns a new array while the reduce() method returns a single object based on the function. You can either create a function beforehand and call it with the methods, or you can directly place the function in between the parenthesis. The syntax and the function of the three different methods are show below.

  • arrayname.filter(function)

    • returns a new array
    • creates a new array where only the elements that meet the criteria in the function are stored
    • returns an empty array if none of the elements meet the criteria
  • arrayname.reduce(function,initial)

    • returns an object, which is the result of the function

    • returns a new array with the same size as the original array
    • each element of the array is changed in the new array, based on the function

Let's start by looking at the filter() method and the new array printed by calling the method. By including the function isEvenNumber when calling the filter() method, only the elements that are even were copied to the new array that was printed. All the odd elements were filtered out of the original array. Next, the reduce() method was used to calculate the sum of the elements in the array. The function is placed directly inside the reduce() method and is used to add all the element of the array. The initial value of the variable sum is 0, which is why the 0 exists in the reduce() method as a second parameter. Finally, the map() function returns a new array of all the elements squared. The function is also directly inside the method in this case and is used to create a new array of the same length.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [1, 2, 9, 16, 25, 36, 49, 64, 81, 100];
function isDivisibleByFive(number) {
    return number % 5 == 0;
arr = arr.filter(isDivisibleByFive);
var squares = (number) {
    return number * number;

What will the following code segment print to the console?