Array Functions: Map, Filter & Reduce
Whenever it comes to functional programming, the uses for map, filter and reduce comes into picture.
These are really useful functions and more over functions these are concepts which are available across languages and frameworks, knowing the concept will help dealing with multiple logics in almost any language even if the language don’t have these functions inbuilt.
These changes the way developer approach the problem, by looking at problem one can guess whether it’s a map, filter or a reduce.
Map
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
filter
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
reduce
The
reduce()
method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
These are language concepts are could be found in most of the languages, few of them are listed below👇
JavaScript
Map
const array1 = [1, 4, 9, 16];// pass a function to map
const map1 = array1.map(x => x * 2);console.log(map1);
// expected output: Array [2, 8, 18, 32]
Filter
const words = [‘spray’, ‘limit’, ‘elite’, ‘exuberant’, ‘destruction’, ‘present’];const result = words.filter(word => word.length > 6);console.log(result);
// expected output: Array [“exuberant”, “destruction”, “present”]
Reduce
const array1 = [1, 2, 3, 4];// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);console.log(sumWithInitial);
// expected output: 10
Kotlin
Map
val numbers = listOf(1, 2, 3)
println(numbers.map { it * it }) // [1, 4, 9]
Filter
val numbers = listOf(“one”, “two”, “three”, “four”)
val longerThan3 = numbers.filter { it.length > 3 }
println(longerThan3)val numbersMap = mapOf(“key1” to 1, “key2” to 2, “key3” to 3, “key11” to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith(“1”) && value > 10}
println(filteredMap)[three, four]{key11=11}
Reduce
val animals = listOf(“raccoon”, “reindeer”, “cow”, “camel”, “giraffe”, “goat”)// grouping by first char and collect only max of contains vowels
val compareByVowelCount = compareBy { s: String -> s.count { it in “aeiou” } }val maxVowels = animals.groupingBy { it.first() }.reduce { _, a, b -> maxOf(a, b, compareByVowelCount) }println(maxVowels) // {r=reindeer, c=camel, g=giraffe}
Clojure
Map
user=> (array-map :a 10)
{:a 10}
user=> (array-map :a 10 :b 20)
{:a 10 :b 20}
user=> (apply array-map [:a 10 :b 20 :c 30])
{:a 10 :b 20 :c 30}
user=> (apply assoc {} [:a 10 :b 20 :c 30]) ;same result using assoc
{:a 10 :b 20 :c 30}
Filter
(filter even? (range 10))
;;=> (0 2 4 6 8)
(filter (fn [x]
(= (count x) 1))
["a" "aa" "b" "n" "f" "lisp" "clojure" "q" ""])
;;=> ("a" "b" "n" "f" "q")
(filter #(= (count %) 1)
["a" "aa" "b" "n" "f" "lisp" "clojure" "q" ""])
;;=> ("a" "b" "n" "f" "q")
; When coll is a map, pred is called with key/value pairs.
(filter #(> (second %) 100)
{:a 1
:b 2
:c 101
:d 102
:e -1})
;;=> ([:c 101] [:d 102])
Reduce
(reduce + [1 2 3 4 5]) ;;=> 15
(reduce + []) ;;=> 0
(reduce + [1]) ;;=> 1
(reduce + [1 2]) ;;=> 3
(reduce + 1 []) ;;=> 1
(reduce + 1 [2 3]) ;;=> 6
Python
Map
def addition(n):return n + nnumbers = (1, 2, 3, 4)result = map(addition, numbers)print(list(result)) // [2, 4, 6, 8]
Filter
def fun(variable):letters = ['a', 'e', 'i', 'o', 'u']if (variable in letters):return Trueelse:return Falsesequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']filtered = filter(fun, sequence)print('The filtered letters are:')for s in filtered:print(s)The filtered letters are:
e
e
Reduce
import functoolslis = [1, 3, 5, 6, 2, ]print("The sum of the list elements is : ", end="")print(functools.reduce(lambda a, b: a+b, lis))print("The maximum element of the list is : ", end="")print(functools.reduce(lambda a, b: a if a > b else b, lis))
The sum of the list elements is : 17
The maximum element of the list is : 6
List more in language of your choice.