There are tons of different ways to code but an efficient way to code is with 'Higher Order Functions'.
These are some of the methods you may have heard of
--> Array.prototype.map, Array.prototype.filter and
Array.prototype.reduce are some of the Higher-Order functions that are built into JS!
Let's start with the
Array.prototype.map -->
The map() method creates a brand new array by calling the callback function on every element in the array.
map() then will take all of those values and return a brand new array. map() uses 3 parameters for it's callback -->
element, index, array.
EX -->
const array = [1, 2, 3, 4, 5];
const multiplied = array.map(function(element) {
return element * 2;
});
console.log(multiplied);
This prints - [2, 4, 6, 8, 10]
Next we have the
Array.prototype.filter -->
The filter() method creates a brand new array with the elements that pass the condition by the callback function.
filter() uses 3 parameters for it's callback -->
element, index array.
EX -->
const friends = [
{ name: 'Bailey', age: 24 },
{ name: 'Jordan', age: 23 },
{ name: 'Merlin', age: 30 },
{ name: 'Rachel', age: 26 },
{ name: 'Nico', age: 23},
];
const older = friends.filter(people => people.age >= 24);
console.log(older);
This Prints - [
{ name: 'Bailey', age: 24 },
{ name: 'Merlin', age: 30 },
{ name: 'Rachel', age: 26 }
]
Our last method of discussion is Array.prototype.reduce() -->
The reduce() method calls the callback function on each element in the array and then gives us a single value. reduce() also has an initialValue available the initialValue does this -->
If the initialValue is provided, the accumulator will equal the initialValue and the currentValue will equal the first element in the array.
If no initialValue is provided, the accumulator will equal to the first element in the array and the currentValue will be equal to the second element in the array.
reduce() uses four parameters for its callback --> accumulator, currentValue(or current), currentIndex(or i), array.
EX without initialValue -->
const array = [5, 7, 1, 8, 4];
const sum = array.reduce(function(accumulator, current) {
return accumulator + current;
});
console.log(sum);
This prints - 25
EX with initialValue -->
const sum2 = array.reduce(function(accumulator, current) {
return accumulator + current;
}, 10); // <-- 10 is the initialValue
console.log(sum2);
This prints - 35
This concludes our into to Higher Order Functions I hope this can be of service to anyone who needs a quick and easy understanding of map(), filter(), and, reduce()!
Top comments (0)