Basic array operations combining Map, Filter & Reduce in JavaScript
Tags: javascript, beginners, webdev, programming
Published: 2022-07-19 06:53:40

**Howdy Folks!** Hope all is good with thee today. Nowadays, it is hard to be coding without applying functional programming concepts to our code, which makes it more readable, maintainable and testable. 

A very common and popular mindset in the modern world of programming is programming in an array-processing style. This implies involving arrays as our fundamental data structure that will process a series of operations on each of its items.

These are useful contexts to apply when populating components  part such as in React where we can use the map() method to iterate through a given array to display its content in this area along with HTML (JSX), and at the same time, using filter() method to remove irrelevant data before using it on a map, or to simple duplicate numerical array items values or get the total of all of them with the reduce method.

Allow me to give you a couple of examples of some cases where we can use the filter(), reduce() and map() methods in JavaScript to find a solution with these modern for loop abstractions. Keep in mind that all of these operations can perfectly be done with a regular for loop, but this time, we are going to get our hands dirty with a functional programming mindset in our JavaScript code, shall we, pals?

Let's start with the example of adding all items of an array. For this, We'll use a classic for loop and a reduce method:

```javascript
const arrNumbers = [1,2,3,4,5,6];

// With plain JavaScript
let total = 0;
for (let i = 0; i < arrNumbers.length; i += 1) {
total += arrNumbers[i];
}

console.log(`The sum of all items is: ${total}`) // should be 21

// Using the Reduce Method this goes like this:
const sumAllItems = arrNumbers.reduce((prev, curr) => prev + curr, 0);

console.log(`Reducing all items to a total of: ${sumAllItems}`) 
// this should also be 21

```

As you can see, in both cases, we had an accumulator, fist is *total* and then is the *sumAllItems* variable, that will keep adding the next item value to the accumulative that they have until the last lap of the loop is completed, pretty cool, right?

Ok, what if I have a request, to build a function that takes in an array of numbers, and a single number as an argument... then this single number sums up with each element in the array: Should we use the regular for loop or simply go functional programming way on this little rascal by using the map method? Well, let's  go ahead and do both of them, ok?

```javascript
// Plain JavaScript Code
function additionWithVanilla(arr, amount) {
  let addNumbers = [];
  for (let i = 0; i < arr.length; i++) {
    addNumbers.push(arr[i] + amount);
  }
  return addNumbers;
}

console.log(additionWithVanilla([1, 2, 3, 4, 5], 8));
// result [ 9, 10, 11, 12, 13 ]

// Same function using EcmaScript 6
const addition = (arr, amount = 0) => arr.map((el) => el + amount);

console.log(addition([1, 2, 3, 4, 5], 8));
// result [ 9, 10, 11, 12, 13 ]

```

Well, that was rather cool, some might say, but what if I only want to have the odd numbers to be the ones being added to a total, pal? Well, in that case, let's do this both ways, functional and classical structured-like programming, ready?

First, by using for loop, we will use a conditional that will sum all odd numbers only. Then, with EcmaScript, we will combine the filter method to return an odd items only array and then use the reduce method to add these items in a whole total to print it afterwards. Too much? here's the example:


```javascript
const arrMixedNumbers = [1, 2, 3, 4, 5, 6];

// With plain JavaScript
let totalOddNumbers = 0;
for (let i = 0; i < arrMixedNumbers.length; i += 1) {
  if (arrMixedNumbers[i] % 2 == 0) {
    totalOddNumbers += arrMixedNumbers[i];
  }
}

console.log(`The sum of all odd numbers: ${totalOddNumbers}`);
// should be 12

// Using the Filter combined with Reduce Method to get the result:
const sumAllOddNumbs = arrMixedNumbers
  .filter((item) => item % 2 == 0)
  .reduce((total, currentValue) => total + currentValue, 0);

console.log(`Filtered Reduction of Odd numbers: ${sumAllOddNumbs}`);
// this should also be 21
```
So folks, as you can see, the sky is the limit when it comes to combine these functional programming mindset methods, however, if you are still in that stage of non-believer, let me just add the last piece of example to convince you:

Let's say we retrieved an array with the names of famous FIFA players and their names are somehow in different Type of cases, however, we want to pass them all to Uppercase, so that they all look cool, how do we do this? Well, folks, let me tell ya how I'd have done it using these methods:


```javascript
const fifaPlayers = [
  "Cristiano Ronaldo",
  "Mohamed salah",
  "robert lewandowski",
  "Leonel MESSI",
  "LUKA Modric",
  "Antoine griezmann",
];
const namesInUppercaseArr = [];

for (let i = 0; i < fifaPlayers.length; i += 1) {
  namesInUppercaseArr.push(fifaPlayers[i].toUpperCase());
}

console.log(namesInUppercaseArr);

// Let's do the same exact thing but using the ES6 map method
console.log(fifaPlayers.map((player) => player.toUpperCase()));

```
## Summary:
Well, folks, the list could continue to expand, but I think is time for me to go to bed. I certainly hope you've enjoyed these basic examples of how to use and combine these methods to achieve these results. 

Thanks for reading this article, I hope you enjoyed it as much as I did writing it. Until next time, dear readers!

❤️ Your enjoyment of this article encourages me to write further.
💬 Kindly share your valuable opinion by leaving a comment.
🔖 Bookmark this article for future reference.
🔗 If this article has truly helped you, please share it.