If you are a front-end developer, day to day you may come across many functions which can confuse you and make it difficult for you to use them appropriately.
In this article, I am going to explain some functions like .map(), .reduce(), filter(), find(), etc. which play an important role when one wants to transform the array of play with JSON responses.
Let’s start with them one by one,
map()
It is an array function that transforms the array according to the applied function and returns the updated array. It works on each element of an array.
Syntax
array.map(callback[,object])
callback - It is a function that provides an element of the new Array from an element of the current one.
object - object to use as this when executing callback.
Return Type - List
Examples
Calculate cube of each element with the help of map.
- function cube(n){
- return n*n*n;
- }
- var arr=new Array(1,2,3,4)
- var newArr=arr.map(cube);
- console.log(newArr) // Output : [1,8,27,64]
In the above example, a function called “cube” is created and then is passed as a callback function into map().
Consider the below example, where er manipulates the array element and transfers it into key and value pairs.
- var arr = [2,5,6,8,9];
- var newArr = arr.map(function(val,index){
- console.log(“Key”:index, “Value”:val*val)
- });
Now, sometimes there could be a list of object like :
- var employees = [
- { id: 20, name: 'Ajay', salary:30000 },
- { id: 24, name: 'Vijay', salary:35000 },
- { id: 56, name: 'Rahul', salary:32000 },
- { id: 88, name: 'Raman', salary:38000 }
- ];
And from the above list, if you wish to create a new list having one property only, like you want the list of salary, then you have to use map() function like :
- var empSalary= employees.map(function(employee) {
- return employee.salary;
- }
- console.log(empSalary) //output => [30000,35000,32000,38000]
filter()
As the name suggests it can filter out the data/array elements on the basis of condition and return the result as a list. Basically, this function pushes the current element into a new array when the callback functions return true.
Syntax
array.map(callback[,object])
callback - it is a function that provides an element of the new Array from an element of the current one.
object - object to use as this when executing callback.
Return Type : List
Examples
- //Calculate a list of even elements from an array :
- arr = new Array(1, 2, 3, 6, 5, 4)
- var newArr = arr.filter(function(record) {
- return record % 2 == 0;
- }); // output => [2,6,4]
Calculate factorial with the help of filter,
- function factorial(value) {
- let ans = 1;
- for (let i = 2; i <= value; i++) ans = ans * i
- return ans;
- }
- var arr = new Array(3, 4, 5, 6)
- var newArray = arr.filter(factorial)
- console.log(newArray) //output=> [6,24,120,720]
Now, sometimes you have a list of object like,
- var employees = [{
- id: 20,
- name: 'Ajay',
- salary: 30000. dept: ’it’
- }, {
- id: 24,
- name: 'Vijay',
- salary: 35000,
- dept: ’hr’
- }, {
- id: 56,
- name: 'Rahul',
- salary: 32000,
- dept: ’it’
- }, {
- id: 88,
- name: 'Raman',
- salary: 38000,
- dept: ’hr’
- }];
And from the above list, if you want to create a new list of IT departments, then you will use filter() function like:
- var departmentList = employees.filter(function(record){
- return record.dept == “it”;
- });
- console.log(departmentList);
- //output [{ id: 20, name: 'Ajay', salary:30000. dept:’it’ }, // { id: 56, name: 'Rahul', salary:32000, dept:’it’ }]
find()
This method returns the value of the first element in the provided array that satisfies the provided testing function. It is very similar to a filter function except that it will find only the first match value. If an element does not satisfy the condition, then it will return #ff0000.
Syntax
array.find(callback[,object])
callback - function to test for each element.
object - object to use as this when executing callback.
- const array1 = [5, 12, 8, 130, 44];
- const found = array1.find(element => element > 10);
- console.log(found);
- //output => 12
As in the above example, there are 3 elements that are greater than 10, but it will display only the first matching element i.e. 12. However, if you will use filter() here then you will get a list of 3 elements, i.e. 12, 130, and 44.
Consider another example with list of objects like,
- var employees = [
- { id: 20, name: 'Ajay', salary:30000 },
- { id: 24, name: 'Vijay', salary:35000 },
- { id: 56, name: 'Rahul', salary:32000 },
- { id: 88, name: 'Raman', salary:38000 }
- ];
-
- var employee= employees.find(function (record) {
- return record.id == 56;
- });
-
- //output :- { id: 56, name: 'Rahul', salary:32000 }
Some methods are very similar to find() like findIndex(), indexOf() and includes(). Let's discuss these methods
findIndex()
This method returns the index of the first element in the array that satisfies the provided testing function.
Example
- const array1 = [5, 12, 8, 130, 44];
- const found = array1.findIndex(element => element > 10);
- console.log(found);
-
- //In above example you will get the position of 12 i.e. 1.
indexOf()
This function is very similar to findIndex(), even this function also returns the index of the first element.
Now, the question that arises is, what is the difference between findIndex() and indexOf()?
The major difference is the parameters of both the functions, i.e.
- indexOf() - expects only a value as the first parameter (not take any callback function). So, it is a better choice to find the index in arrays of primitive types like number, string, and boolean.
- findIndex() - expects a callback as the first parameter. By the help of this callback function, you will give a condition to find an element. So, it is a better choice to use this when you need the index in arrays with non-primitive types (e.g. objects) or your find condition is more complex than just a value.
includes()
It is similar to indexOf(), i.e. both can be used to find elements in an array, however, indexOf() returns a number (-1 if element not present in the array, or array position if the element is present). But, includes() returns a boolean value (true or false)
reduce()
It also works on a callback for each element of an array. It reduces the result of this callback function from one array element to the other.
Syntax
array.reduce(callback[,initalValue])
callback - this parameter is the function to execute on each value in the array.
intitalValue - this parameter is the object to use as the first argument of the first call of the callback.
Examples
To calculate product of every element of an array,
- var arr = new Array (1,2,3,4,5)
- var val = arr.reduce(function(a,b){
- return a*b;
- });
- //output => 120
Calculate the total salary from a list of object, then you will use the reduce() like,
- var employees = [
- { id: 20, name: 'Ajay', salary:30000 },
- { id: 24, name: 'Vijay', salary:35000 },
- { id: 56, name: 'Rahul', salary:32000 },
- { id: 88, name: 'Raman', salary:38000 }
- ];
- var totalSalary= employees .reduce(function (total, record) {
- return total + record.salary;
- }, 0);
-
- //It will return the total salary of all the employees.
This all about the basic use of the above function. Now, let’s consider one more example where there is a complex list of objects and one has to find data on the basis of condition.
- var employees= [
- { id: 10, name: "Ajay", years: 14, salary:40000, dept:'it' },
- { id: 2, name: "Vijay", years: 30, salary:35000, dept:'hr' },
- { id: 41, name: "Rahul",years: 16, salary:45000, dept:'hr'},
- { id: 99, name: "Raman",years: 22, salary:35000,dept:'it'}
- ];
Now, from the above data, suppose you have to calculate total salary on the basis of department, then the below code would be used where filter(), reduce() and map() function can be mixed.
- var deptList = [...new Set(pilotList.map(function(item) {
- return item.dept;
- }, 0))];
- //with the help of above code first all the unique department list is found i.e it will return [‘it’,’hr’], now on the basis of that list the total will be found.
- var deptList1 = deptList.map(function(item) {
- var totalSal = employees.filter(function(record) {
- return record.dept === item
- }).reduce(function(tot, employee) {
- return tot + employee.salary;
- }, 0)
- return {
- 'dept': item,
- 'total': totalSal
- }
- }, 0);
- //output : {'dept':'it', 'total':75000} {'dept':'hr', 'total':80000}
Summary
It may be a little tricky to remember all the functions and their use. So, for this here is a picture that anyone can easily memorize.
Conclusion
Through this article, the use of .map(), filter(), reduce() and other functions can be understood in a better way.
I hope after reading this article, you can easily use these functions. All the queries related to this article are always welcomed. Thanks for reading.!!!