Sunday, November 18, 2018

Introduction To map(), reduce(), and filter() function in javascript

This tutorial explains how to use map(), reduce(), and filter() function in javascript programming language. Nowadays these function are widely used during react and react native application development.

These are 3 really powerful array functions:
  1. map returns an array with the same length,
  2. filter as the name implies, it returns an array with less items than the original array
  3. reduce returns a single value (or object)
NOTE : map, filter and reduce were introduced in ES5, so you can safely use them as implemented in every browser.

Introduction To map(), reduce(), and filter() function in javascript




map() :

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Syntax :
array.filter(function(elem, index, array) {
      ...
}, thisArg);

parammeaning
elemelement value
indexindex in each traversal, moving from left to right
arrayoriginal array invoking the method
thisArg(Optional) object that will be referred to as this in callback

Example - 1 :
In this example we are iterating each array element and multiply each element of array with 10.
var arr = [1, 4, 9, 16];

// pass a function to map
const map1 = arr.map(x => x * 10 );

console.log(map1);

Output:
-----------
> Array [10, 40, 90, 160]

Example - 2 :
in this example we are going extract id attribute value from the array element.
var officers = [
  { id: 1, name: 'Android' },
  { id: 2, name: 'Php' },
  { id: 3, name: 'React' },
  { id: 4, name: 'React Native' }
];

we will extract id attribute value form array element using map function and output should be like this :
[1, 2, 3, 4]

lets see the complete example :
var arr = [
  { id: 1, name: 'Android' },
  { id: 2, name: 'Php' },
  { id: 3, name: 'React' },
  { id: 4, name: 'React Native' }
];

var ids = arr.map(function (arr) {
  return arr.id
});

// or using ES6 syntax
var ids1 = arr.map(arr => {  return arr.id} );

console.log(ids)
console.log(ids1)

Output:
-----------
> Array [1, 2, 3, 4]
> Array [1, 2, 3, 4]

Example - 3 :
In this example we will extract data from the array element and return object as a result.
var arr = [1,2,3,4];

var newArr = arr.map((val, i, arr) => {
  return {
    value: val * 2,
    index: i
  };
});

console.log(newArr)

Output:
-----------
> Array [Object { value: 2, index: 0 }, Object { value: 4, index: 1 }, Object { value: 6, index: 2 }, Object { value: 8, index: 3 }]

Example - 4 :
In this example we are using map function without passing any parameter during function call as it is optional one.
var arr = [1,2,3,4];

var newArr = arr.map(() => {
  return 'AAA';
});

console.log(newArr)

Output:
-----------
> Array ["AAA", "AAA", "AAA", "AAA"]

reduce()

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

Syntax :
array.reduce(function(prevVal, elem, index, array) {
      ...
}, initialValue);

parammeaning
prevValuecumulative value returned thru each callback
elemelement value
indexindex of the traversal, moving from left to right
arrayoriginal array invoking the method
initialValue(Optional) object used as first argument in the first (leftmost) callback.
In this example, we will see work flow of reduce method in javascript application. Lets see the below array object :
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];

From this array, we will do below operations :
1. Calculate the sum score attribute.
2. Find the highest score element from the array.
3. Find the lowest score element from the array.

Calculate the sum score attribute.
Here we will calculate the sum of score from array elements.
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];

var totalScore = arr.reduce(function (accumulator, arr) {
  return accumulator + arr.score;
}, 0);

// or using ES6 syntax
var totalScore1 = arr.reduce((accumulator, arr) => {
  return accumulator + arr.score;
}, 0);

console.log(totalScore)
console.log(totalScore1)

Output:
-----------
> 100
> 100

Find the highest score element from the array.
Here we will find the highest score element from the array.
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];
// get highest score element
var hightscore = arr.reduce(function (oldest, newarr) {
  return (oldest.score || 0) > newarr.score ? oldest : newarr;
}, {});

console.log(hightscore)

Output:
-----------
> Object { id: 3, name: "React", score: 40 }

Find the lowest score element from the array.
Here we will find the lowest score element from the array.
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];
// get lowest score element
var lowscore = arr.reduce(function (oldest, newarr) {
  return (newarr.score || 0) > oldest.score ? oldest : newarr   ;
}, {});

console.log(lowscore)

Output:
-----------
> Object { id: 2, name: "Php", score: 10 }

Searching data in array using reduce function.
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];

const filterdata = arr.reduce((result, item) => {
  if (item.id === 3) { result = item }
  return result
}, null)

console.log(filterdata)

Output:
--------------------
> Object { id: 3, name: "React", score: 40 }

filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Syntax:
array.filter(function(elem, index, array) {
      ...
}, thisArg);

parammeaning
elemelement value
indexindex in each traversal, moving from left to right
arrayoriginal array invoking the method
thisArg(Optional) object that will be referred to as this in callback
In this example we are to filter the array element by name and score attribute.

Example -1 :
We are filtering the array element whose score is equal to 40.
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];
// filter element by score
var score = arr.filter(function (newarr) {
  return newarr.score === 40;
});

// or using ES6 syntax
var score1 = arr.filter(newarr =>  newarr.score === 40 );
                      

//console.log(score)
console.log(score1)

Output:
-----------
> Array [Object { id: 3, name: "React", score: 40 }]

Example -2 :
We are filtering the array element whose name is equal to Php.
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];
// filter element by name
var nameval = arr.filter(function (newarr) {
  return newarr.name === "Php";
});

// or using ES6 syntax
var nameval1 = arr.filter(newarr =>  newarr.name === "Php" );
                      

console.log(nameval)
console.log(nameval1)

Output:
-----------
> Array [Object { id: 2, name: "Php", score: 10 }]
> Array [Object { id: 2, name: "Php", score: 10 }]

Example -3 :
We are filtering the array element whose score is greater than 20.
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];
// filter element by score
var score = arr.filter(function (newarr) {
  return newarr.score > 20;
});

// or using ES6 syntax
var score1 = arr.filter(newarr =>  newarr.score > 20 );
                      

console.log(score)
console.log(score1)

Output:
-----------
> Array [Object { id: 3, name: "React", score: 40 }, Object { id: 4, name: "React Native", score: 30 }]
> Array [Object { id: 3, name: "React", score: 40 }, Object { id: 4, name: "React Native", score: 30 }]

Example -4 :
We are filtering the array element with multiple parameters.
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];
// filter element by score
var score = arr.filter(function (newarr) {
  return newarr.score > 20 && newarr.name.startsWith("R") && newarr.name.endsWith("e");
});                

console.log(score)

Output:
-----------
> Array [Object { id: 4, name: "React Native", score: 30 }]

This is all about map(), reduce(), and filter() function in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.



No comments:

Post a Comment