logo

Functional Javascript: 4 Useful Array Methods

Functional programming has always been a paradigm loved by developers across different fields. It not only reduces bugs in our code by reducing side effects, but also increases code reusability by allowing developers to reuse their functions without much hassle.

Like functional programming, an array is a ubiquitous data structure. This article is going to share some native array methods that I have found useful throughout my coding endeavour.

map()

It takes in a function as its parameter and calls the provided function with each of the array elements as the parameter. This method returns a new array as its output.

Provided Function

const addTwo = (number) => number + 2;

Example

const numbers = [1,2,3,4,5];
const plusTwo = numbers.map(addTwo); // addTwo is defined in Provided Function section
    
console.log(plusTwo) 
// [3,4,5,6,7]

reduce()

This method takes a function and an initial value as its parameters. It reduces the array elements into a single element by calling the provided function with the array elements.

Provided Function

const add = (total, currentNumber) => total + currentNumber;

Example

const numbers = [1,2,3,4,5];
const total = numbers.reduce(add, 0);
    
console.log(total);
// 15

Step-by-step

const numbers = [1,2,3,4,5];
const total = numbers.reduce(add, 0);
    
1.
total = 0 (initial value)
currentNumber = 1 (first array element)
returnValue = 1 (total + currentNumber)
      
2. 
total = 1 (last return value)
currentNumber = 2 (second array element)
return = 3 (total + currentNumber)
.
.
.

5.
total = 10
currentNumber = 5
final return = 15

filter()

The filter method accepts a function as its parameter. The provided function is used to perform filtering checks on the array elements. It doesn’t mutate the original array.

Provided Function

const isGreaterThan5 = (arrayElement) => arrayElement > 5;

If the provided function returns True, the array element is kept. If it returns False, the array element is discarded.

Example

const numbers = [1,2,3,4,5,6,7,8];
const result = numbers.filter(isGreaterThan5);
    
console.log(result);
// [6,7,8]

slice()

This method takes in two numbers as its parameters which indicates the starting index and ending index for slicing. This method does not mutate the original array.

The result of this method does not include the array element which is on the ending index.

Example

const food = ['chocolate', 'sushi', 'steak', 'chips'];
const result = food.slice(0, 2);
    
console.log(result);
// ['chocolate', 'sushi']

You can also use slice for duplication too (shallow copy).

Example

const food = ['chocolate', 'sushi', 'steak', 'chips'];
const result = food.slice();
    
console.log(result);
// ['chocolate', 'sushi', 'steak', 'chips']