DEV Community

Amnah Khatun
Amnah Khatun

Posted on

Mastering Array Manipulation with Map, Filter, and Reduce in JavaScript

The methods of map, filter, and reduce are widely used by developers and are commonly asked in interviews. Understanding these methods and knowing where to apply them is important. In this article, you will also learn how to create your own custom methods.

Let's start…

MAP
As per mdn: The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

map() is used to transform the array's values and return the new array. It is generally used when you have to run an operation for each value in the array. 

Here's the general syntax:
const arr = [1, 2, 3, 4, 5]
let transformedArray = arr.map((item) => {
return item * 2
})
console.log(transformedArray) //[ 2, 4, 6, 8, 10 ]

Here's an example of a custom map() method:

const arr = [1, 2, 3, 4, 5]
Array.prototype.myMap = function (cb) {
let newArr = [];
for (let arr of this) {
newArr.push(cb(arr))
}
return newArr;
}
let transformedArray = arr.myMap((item) => {
return item * 2
})
console.log(transformedArray) //[ 2, 4, 6, 8, 10 ]


FILTER
As per mdn, filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
In simple words, filter is used to filter out the array. It returns the array with values that successfully passed the provided condition.

Here's the general syntax:
const arr = [1, 2, 3, 4, 5]
let transformedArray = arr.filter((item) => {
return item > 2
})
console.log(transformedArray)// [ 3, 4, 5 ]

Here's an example of a custom filter() method:

const arr = [1, 2, 3, 4, 5];
Array.prototype.myFilter = function (cb) {
const filtered = [];
for (let el of this) {
if (cb(el)) {
filtered.push(el);
}
}
return filtered;
};
const filteredData = arr.myFilter((item) => {
return item > 2
});
console.log(filteredData) //[3,4,5]


REDUCE
As per the mdn, reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, to pass 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.
To break it down in simple words, remember that reduce is used when you have to iterate over the array and find a particular value. It takes two parameters: the first is the callback function(cb), and the second is the initialValue, which is passed to the accumulator.
reduce(callbackFn, initialValue)

The callback function takes two parameters, accumulator(acc) and current value(curr). 
reduce(function (acc, curr) { /* … */ })

The accumulator is the result from the previous call of callback function(cb). On the first call, in the case initialValue is not provided, the default value is array[0]. curris the value of the current element.
If initialValue is specified, cb starts executing with the first value in the array as curr. If initialValue is not specified, acc is initialized to the first value in the array, and cb starts executing with the second value in the array as curr. In this case, if the array is empty (so that there's no first value to return as accumulator), an error is thrown.

Here's the general syntax:

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, curr) => {
acc = acc + curr;
return acc
},0)
console.log(sum) //15

If we will log acc and curr

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, curr) => {
console.log('acc--> ' + acc, 'curr--> ' + curr)
acc = acc + curr;
return acc
}, 0)
//log output
acc--> 0 curr--> 1
acc--> 1 curr--> 2
acc--> 3 curr--> 3
acc--> 6 curr--> 4
acc--> 10 curr--> 5

Here's an example of a custom reduce() method:

const arr = [1, 2, 3, 4, 5];
Array.prototype.myReduce = function (cb, value) {
let a = this;
for (let el of this) {
value = value !== undefined ? cb(value, el) : el;
}
return value;
};
const sum = arr.myReduce(function (acc, curr) {
return acc + curr;
}, 0);
console.log(sum); //15

Conclusion
In conclusion, map, filter, and reduce are powerful methods that can be used to transform, filter, and calculate values in arrays. By understanding these methods and knowing where to apply them, you can greatly improve the efficiency and readability of your code. In addition, creating your own custom functions based on these methods can provide even more flexibility in your programming. Whether you're a beginner or an experienced developer, mastering map, filter, and reduce is essential to writing high-quality code. So, make sure to practice and experiment with these methods to become a more proficient programmer.
Thank you and happy coding ✌️

Top comments (0)