How array methods work internally => Map || Filter || Reduce
Map
We discovered the power of map
, which enables us to create a new array by applying a transformation to each element of an existing array. By understanding the internal workings of, we gained insights into how it functions its magic behind the scenes
var map = function(arr, fn) {
let n=arr.length;
let arr2=[];
for(let i=0;i<n;i++){
arr2.push(fn(arr[i],i));
}
return arr2;
};
Filter
The enchantment of filter
captivated us as we learned how to extract specific elements from an array based on certain conditions. By exploring the inner mechanics of filter
, we demystified how it selectively handpicks elements.
var filter = function(arr, fn) {
let n=arr.length;
let arr2=[];
for(let i=0;i<n;i++){
if(fn(arr[i],i))
arr2.push(arr[i]);
}
return arr2;
};
uses of filter ||how to use filter ||where to use filter
Reduce
We ventured into the realm of reduce
, where we learned to elegantly accumulate an array into a single value using a combination of elements and a callback function. By peering into the internal mechanisms of reduce
, we uncovered its ability to perform powerful aggregations.
var reduce = function(nums, fn, init) {
for(let i=0;i<nums.length;i++){
init=fn(init,nums[i]);
}
return init;
};
Subscribe to my newsletter
Read articles from BISHAL DATTA directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by