Python equivalent of JavaScript map, reduce, filter
When we write code in Python, we often use functions like reduce, map, and filter to work with collections like lists. These functions help us perform operations on each item in the collection in a clean and efficient way. JavaScript also provides similar functionality, and today we will explore how we can do the same tasks in JavaScript.
Table of Content
map in JavaScript
In Python, we use map to apply a function to every item in a list and return a new list. JavaScript has a similar method called map.
lst = [1, 2, 3]
result = list(map(lambda x: x * 2, lst))
print(result)
Output
[2, 4, 6]
let arr = [1, 2, 3]
let result = arr.map(a => a * 2)
console.log(result)
filter in JavaScript
The filter function in Python helps us keep only those items in a list that meet a certain condition. JavaScript has a filter method that does exactly the same thing.
lst = [1, 2, 3, 4]
result = list(filter(lambda x: x % 2 == 0, lst))
print(result)
Output
[2, 4]
let arr = [1, 2, 3, 4]
let result = arr.filter(a => a % 2 === 0)
console.log(result)
reduce in JavaScript
Python’s reduce function is used to reduce a list to a single value. In JavaScript, reduce does the same job. It takes a function that is applied to every element, and it returns a single value.
from functools import reduce
lst = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, lst)
print(result)
Output
10
let arr = [1, 2, 3, 4]
let result = arr.reduce((a, b) => a + b, 0)
console.log(result)
- The reduce method takes a function with two arguments, a and b. It applies the function to each element in the array and combines the results into a single value.
- The second argument to reduce (0 in our example) is the initial value. Without it, the first element of the array is used as the initial value.