visit
When I started learning modern JavaScript (or ES6 😏), array methods were one of the most challenging things for me to wrap my head around. I had no idea what to do with these maps
, filters
, reduce
& stuff. Thankfully, now I understand them.
To understand this post, you'll need an understanding of for loops, arrays (duh), functions (also arrow functions), callbacks & the ability to interpret code 🌝. You should be able to read the example code & understand what each method does under the hood. Btw if you don't know what callbacks are, here's my explanation.
A callback function is just a function that is passed as an argument to another function, and this callback function will be then called back (callback get it? 🤯) internally when it's needed.
function cb() {
console.log("this is my callback function...");
}
function someStuff(cb) {
// doing some stuff...
console.log("done with it...");
// maybe doing some more stuff...
cb();
// again doing something...
}
someStuff(cb);
done with it...
this is my callback function...
someStuff(() => {
console.log("this is my callback function...");
});
someStuff(function () {
console.log("this is my callback function...");
});
The JavaScript map method 'transforms' an array into a new array by calling a callback function on each element, and populating the resultant array with its return value. The reason I enclosed 'transforms' in quotes is because it does not actually modify the original value.
function map(arr, callback) {
const result = [];
for (let i = 0; i < arr.length; ++i) {
result.push(callback(arr[i], i));
}
return result;
}
const numbers = [2, 4, 9, 10];
const squares1 = numbers.map((num) => num ** 2);
const squares2 = map(numbers, (num) => num ** 2);
console.log(squares1);
console.log(squares2);
[ 4, 16, 81, 100 ]
[ 4, 16, 81, 100 ]
result = [] (initially)
2 ** 2 = 4 [4]
4 ** 2 = 16 [4, 16]
9 ** 2 = 81 [4, 16, 81]
10 ** 2 = 100 [4, 16, 81, 100]
returns [4, 16, 81, 100]
The filter method is essentially used to filter out some elements based on some tests. The callback function for filter should return a boolean, which will be used to determine which elements will be there in the resultant array. If the callback returns true for the current element, only then it will be added to the resultant array.
function filter(arr, callback) {
const result = [];
for (let i = 0; i < arr.length; ++i) {
if (callback(arr[i], i)) {
result.push(arr[i]);
}
}
return result;
}
const numbers = [0, -1, 4, -10, 5, 10, 100, -22];
const negatives1 = numbers.filter((num) => num < 0);
const negatives2 = filter(numbers, (num) => num < 0);
console.log(negatives1);
console.log(negatives1);
[ -1, -10, -22 ]
[ -1, -10, -22 ]
result = [] (initially)
0 < 0 = ❌ []
-1 < 0 = ✅ [-1]
4 < 0 = ❌ [-1]
-10 < 0 = ✅ [-1, -10]
5 < 0 = ❌ [-1, -10]
10 < 0 = ❌ [-1, -10]
100 < 0 = ❌ [-1, -10]
-22 < 0 = ✅ [-1, -10, -22]
returns [-1, -10, -22]
The reduce method is used to perform some operation on the array & somehow 'reduce it' to a single value. Basically, just take an array, do something on it & just return a single value. The callback for this method would take 2 arguments: accumulator
& current value
. The current value argument is the same old element at the current index, but what is this accumulator though?
The accumulator is just a variable that is given some initial value (or it would be set to the first element in the array by default) which then stores (or accumulates 🌝) the value that is returned by the callback.
Finally, this value is then returned by reduce()
. The most common example of this would be to calculate the sum of all the elements in an array, and I think that reading the code would be better than reading my words.
function reduce(arr, callback, initialValue) {
let accumulator = initialValue;
let start = 0;
if (arguments.length !== 3) {
accumulator = arr[0];
start = 1;
}
for (let i = start; i < arr.length; ++i) {
accumulator = callback(accumulator, arr[i], i);
}
return accumulator;
}
const numbers = [-1, 5, 2, -3, 10];
const sum1 = numbers.reduce((a, c) => a + c, 10);
const sum2 = reduce(numbers, (a, c) => a + c, 10);
console.log(sum1);
console.log(sum2);
23
23
Now here's what's gonna happen (I'm gonna refer to accumulator
as acc
:
acc = 10 (initially)
acc = 10 + -1 = 9
acc = 9 + 5 = 14
acc = 14 + 2 = 16
acc = 16 + -3 = 13
acc = 13 + 10 = 23
returns 23
reduce()
, then it would've been:acc = -1 (default: first element of the array)
acc = -1 + 5 = 4
acc = 4 + 2 = 6
acc = 6 + -3 = 3
acc = 3 + 10 = 13
returns 13
Also published here.