If you are starting in the web development, maybe you haven’t heard about the functional programming.

Functional programming has been making prominent space in the field of web development. It will help you to write more precise and clean code which is easy to understand, refactor and test. There is some javascript array method available by using them you can achieve the functional programming easily in Javascript.

In this article, we are going to learn the big three javascript array methods which simplify your codebase and increase your productivity.

Here, we are going to learn about the best use case of the map(), filter(), reduce() array methods of the Javascript.

Find And Replace The key-value Pair in an Array of Object

While the development of any app, there is a time when we want to update the value of an array of objects using its key.

By using the javascript array map() function we can easily do that within a second.

Let’s take an example below, we have a list of a person which consist his name, experience, designation and id like below.

const personObject = [
    {
         "id":1,
         "name": "A",
         "experienceInYear": 5,
         "designation" : "senior associate" 
    },
    {
         "id":2,
         "name": "B",
         "experienceInYear": 3,
         "designation" : "associate"
    },
    {
         "id":3,
         "name": "C",
         "experienceInYear": 6,
         "designation" : "senior"
    }
]

Now, what we need is to update the designation of the person to lead whose year of experience is greater than6. So we can do that simply by using the below code:

const personObject.map(p => p.experienceInYear >= 6 ? {...p,designation: "lead"} : p)

It’s pretty simple and clean but will take some time to understand if you don’t have good knowledge in js map() function.

Flattening an array of arrays

Suppose you have an array of arrays like below and want to get a single array of all values then you can do that simply by using the javascript reduce() method.

const aoa = [[1,2,3],[4,5,6],[7,8,9]];

const flatteredArr = aoa.reduce((acc,arr) => [...acc , ...arr]);

Simple Search within Array

You can use the javascript filter() method to filter the array by providing the condition in the callback method.

Case-Insensitive

const employees = [
  { id: 101, name: 'john', group: 'tech-lead' },
  { id: 102, name: 'sam', group: 'associate' },
  { id: 103, name: 'danny', group: 'senior associate' },
  { id: 104, name: 'ketty', group: 'senior associate' },
  { id: 105, name: 'mili', group: 'junior' },
  { id: 106, name: 'mouli', group: 'senior associate' },
  { id: 107, name: 'George', group: 'senior associate' }
];

let res = employees.filter(it => new RegExp('li', "i").test(it.name));

Case-sensitive

const employees = [
  { id: 101, name: 'john', group: 'tech-lead' },
  { id: 102, name: 'sam', group: 'associate' },
  { id: 103, name: 'danny', group: 'senior associate' },
  { id: 104, name: 'ketty', group: 'senior associate' },
  { id: 105, name: 'mili', group: 'junior' },
  { id: 106, name: 'mouli', group: 'senior associate' },
  { id: 107, name: 'George', group: 'senior associate' }
];

let res = users.filter(it => it.name.includes('li'));

Find the sum of a list of numbers

Let’s say you have an array of numbers and you want to find the total sum of that numbers then you can easily do that with the reduce method like below:

const numbers = [1,2,3,4,5,6,7,8,9];

const sum = numbers.reduce((acc,number) => acc+number);

Here, we are not passing any default value for the acc argument, you also pass the default value like below:

const sum = numbers.reduce((acc,number) => { return acc+number }, 0);

Separate Odd and Even Numbers from the Array

This is just a simple example but you can use this in your code mostly place where you have to separate the data according to their groups.

const numbers = [1,2,3,4,5,6,7,8,9];

const { evenNumbers, oddNumbers} = numbers.reduce((obj,number) => {
		if( number % 2 === 0){
            obj.evenNumbers.push(number);
        }else{
            obj.oddNumbers.push(number);
        }

		return Object.assign({},obj);
	},{
		evenNumbers : [],
		oddNumbers : []
	});

console.log(evenNumbers);   // (4) [2,4,6,8]
console.log(oddNumbers);    // (5) [1,3,5,7,9]

Filter Nested Arrays

I am sure many of you face this problem once in your coding life to filter values from the nested arrays. If you don’t know the right way of doing this then you will surely waste lots of time doing this.

Here, I am taking a simple example where we filter the nested values.

const arr = [
    [{ id : 1, name: "a" },{ id : 2, name: "b" }],
    [{ id : 3, name: "c" },{ id : 4, name: "d" }]
] 

const filteredArr = arr.reduce((a,b) => a.concat(b))
            .filter((obj) => obj.id === 3);

console.log(filteredArr)

In the above code, first, we are reducing the array and then filter it by our desired value.

Find the count of the specified key in array

By using the javascript array reduce method we can easily find the count of the specified key in an array.

Let’s take the below example:

const employees = [
  { id: 101, name: 'john', group: 'tech-lead' },
  { id: 102, name: 'sam', group: 'associate' },
  { id: 103, name: 'danny', group: 'senior associate' },
  { id: 104, name: 'ketty', group: 'senior associate' },
  { id: 105, name: 'mili', group: 'junior' },
  { id: 106, name: 'mouli', group: 'senior associate' },
  { id: 107, name: 'George', group: 'senior associate' }
];

In the above example, we need to get the number of employees in each group. At first, it looks difficult but you can easily achieve that by using the below code:

Conclusion

After reading this article, I hope you have some idea on how to use javascript array method map(), filter() and reduce() in your code to simply the things.

Here, I want to mention one thing, In all the above examples you’ve seen that they all to avoid mutating state which if you use for and forEach loop then it requires.

This is just a few examples, you can do a lot of things and clean your code which is easy to understand and read for others.

If you like this article then share it with your friends and other social media 🙂

Codecademy Web Development
Pin It