Array Methods for Functional Programming

Functional programming is a paradigm which avoids changing state and mutable data. Functional way of writing a program is using pure functions and immutable data structures. JavaScript comes with many in-bulit functions to support this functional approach.

In this article, we would be learning about a few such methods to manipulate arrays in a functional way. These methods are higher order functions i.e. they require a callback as an argument. Have a look at my previous blog to get a quick review about arrow functions.

Map

The map() method iterates over each array element and executes the callback function for them. It returns a new array without altering the original one.

Callback can take 3 parameters.

  • Current Value (required)
  • Index
  • Array

Callback returns the manipulated element.

map() can optionally take a second parameter (thisArg) which specifies the value of 'this' to be used.

Syntax

array.map(function(currentValue, index, array) { return statement }, thisArg)

Example

const numbers = [1, 44, 66, 11, 43]
const tripledNumbers = numbers.map(num => num * 3)
console.log(tripledNumbers)
// [3, 132, 198, 33, 129]

Filter

The filter() method iterates over each array element, applies the callback and returns an array consisting of element matching the criteria.

Callback can take 3 parameters.

  • Current Value (required)
  • Index
  • Array

Callback returns a boolean value which is used to construct the new array.

filter() can optionally take a second parameter (thisArg) which specifies the value of 'this' to be used.

Syntax

array.filter(function(currentValue, index, array) { return statement }, thisArg)

Example

const numbers = [1, 44, 66, 11, 43]
const oddNumbers = numbers.filter(num => num % 2)
console.log(oddNumbers)
// [1, 11, 43]

Reduce

The reduce method applies the supplied reducer function and return a single value. In other words, it reduces the array into a single value without mutating the original array.

Callback or the reducer function can take 4 parameters.

  • Previous Value (required)
  • Current Value (required)
  • Current Index
  • Array

Callback returns a value which is used as the previous value in the next iteration.

reduce() can optionally take a second parameter (initialValue) to be used as previousValue in the first iteration while currentValue is set to the first element.

If nothing is provided, previousValue is initialized to the first element and currentValue is initialized to the second element.

Syntax

array.reduce(function(previousValue, currentValue, currentIndex, array) { return statement }, initialValue)

Example

const numbers = [1, 44, 66, 11, 43]
const sum = numbers.reduce((acc, curr) => acc + curr, 0)
console.log(sum)
// 165

Find

The find() method check the array elements for set condition and returns the first occurrence. It is similar to filter but unlike filter which returns all matched elements in an array, find will return the first matched element.

Callback can take 3 parameters.

  • Current Value (required)
  • Index
  • Array

Callback returns a truthy value if element is found and in such cases the value is immediately returned terminating further iterations.

find() can optionally take a second parameter (thisArg) which specifies the value of 'this' to be used.

Syntax

array.find(function(currentValue, index, arr),thisValue)

Example

const numbers = [1, 44, 66, 11, 43]
const multipleOf4 = numbers.find(num => num % 4 === 0 )
console.log(multipleOf4)
// 44

Every

The every() method tests whether all elements in the array pass the test provided as a callback and returns a Boolean value.

Callback can take 3 parameters.

  • Current Value (required)
  • Index
  • Array

Callback returns a Truthy or Falsy value according to the test function results. Incase of a falsy value, a boolean value of false is immediately returned terminating further iterations.

every() can optionally take a second parameter (thisArg) which specifies the value of 'this' to be used.

Syntax

array.every(function(currentValue, index, arr),thisValue)

Example

const numbers = [1, 44, 66, 11, 43]
const isNaturalNumber = numbers.every(num => num !== 0 )
console.log(isNaturalNumber)
// true

Some

The some() method tests whether atleast one element in the array pass the test provided as a callback and returns a Boolean value.

Callback can take 3 parameters.

  • Current Value (required)
  • Index
  • Array

Callback returns a Truthy or Falsy value according to the test function results. Incase of a truthy value, a boolean value of true is immediately returned terminating further iterations.

some() can optionally take a second parameter (thisArg) which specifies the value of 'this' to be used.

Syntax

array.some(function(currentValue, index, arr),thisValue)

Example

const numbers = [1, 44, 66, 11, 43]
const containsEvenNumber = numbers.some(num => num % 2 == 0 )
console.log(containsEvenNumber)
// true

Bonus: Converting Sort to functional approach

The sort() method sorts the array in place which means it mutates the original array. But, instead of directly providing the original array to the sort function, we can provide a copy of the array using the (...) spread operator. This will ensure that the original array stays unchanged

Example

const numbers = [1, 44, 66, 11, 43]
const sortedNumbers = [...numbers].sort((a, b) => a - b)
console.log(`Original Array : ${numbers}`)
console.log(`New Array : ${sortedNumbers}`)
// Original Array : [1, 44, 66, 11, 43]
// New Array : [1, 11, 43, 44, 66]

Points to note

  • Reduce is a general purpose method and can be used to implement any of the above mentioned methods.

Example

const numbers = [1, 44, 66, 11, 43]
const tripledNumbers= numbers.reduce((acc, curr) => [...acc, curr * 3], [])
console.log(tripledNumbers)
// [3, 132, 198, 33, 129]
  • Map and Filter (also reduce if it returns an array) can be chained together will other methods.

Example

const numbers = [1, 44, 66, 11, 43]
const tripledOddNumbers = numbers.map(num => num * 3)
                                 .filter(num => num % 2)
console.log(tripledOddNumbers)
// [3, 33, 129]

Summary

  • In this blog we learned about various array methods (viz. map, filter, reduce, find, ,every, some ) which follow the functional programming approach.
  • We also saw a way to use the non-functional sort method in a functional way.
  • Reduce can be used to mimic the behaviour of other array methods
  • Map and Filter can be chained with other methods