Skip to main content

Using map(), reduce() and filter() array methods to nail Javascript manipulation

While working on a real life project we often have front end separated from backend by API, which is a standard modern method as of today. But the data given by backend API is not always favorable for the frontend. And such scenario in real life is imminent and it is not always possible to write a new API for every desirable data in frontend which can be manipulated. But this scenario is not necessarily only useful on frontend, but also could prove very significant on backend too. 

map creates a new array by transforming every element in an array, individually. filter creates a new array by removing elements that don't belong. reduce, on the other hand, takes all of the elements in an array, and reduces them into a single value.

map → Executes a function on each element of an array
filter → Remove items which don’t satisfy a condition
Reduce → Creates a single value from elements of Array


Array.prototype.map()



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

array.map(function(currentValue, index, arr), thisValue)
Understanding how the callback function in 
map works is crucial to using the Map Method effectively.  The Map Method's callback takes three arguments, although you can write a callback only using one or two arguments as well. Here are the three arguments that it takes: 
array.map((value, index, array) => { ... })

function(currentValue, index, arr):
  • currentValue: It is required parameter and it holds the value of current element.
  • index: It is optional parameter and it holds the index of current element.
  • arr: It is optional parameter and it holds the array.

Another scenario :
  
  
//Suppose you have an array of objects like this

var arr = 
[{
  id: 1,
   name: 'bill'
}, 
{
  id: 2,
  name: 'ted'
}]

//and you want this array of objects to twist into something like this

[{
  text: "bill",
  value: 1
}, {
  text: "ted",
  value: 2
}]

//Mapping can easily perform this manipulation 

var result = arr.map(person => {
return ({ value: person.id, text: person.name })
})
console.log(result)
Keep in mind that the resulting array will always be the same length as the original array.

Array.prototype.reduce()


Just like .map().reduce() also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other.

callback

A function to execute on each element in the array (except for the first, if no initialValue is supplied).

reduce passes your callback four arguments:

  1. The Accumulator
    • The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied. On each iteration, inside the callback we perform some operation and that will be added to the accumulator. 
  2. The current value 
  3. The current index
  4. The array you called reduce on
Notice that the callback gets a previous value on each iteration. On the first iteration, there is no previous value. This is why you have the option to pass reduce an initial value: It acts as the "previous value" for the first iteration, when there otherwise wouldn't be one.


var pilots = [
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
    id: 41,
    name: "Tallissan Lintra",
    years: 16,
  },
  {
    id: 99,
    name: "Ello Asty",
    years: 22,
  }
];

const totalYears = 
 pilots.reduce((acc, pilot) => acc + pilot.years, 0);
 
//Output :82

Notice that I’ve set the starting value as 0. I could have also used an existing variable if necessary. After running the callback for each element of the array, reduce will return the final value of our accumulator (in our case: 82).





Comments

Popular posts from this blog

How to connect php to mysql database? Simple html comment box tutorial.

First thing first. You will need a little bit knowledge of web programming. Simple HTML will work. Now here is a step by step procedure on how to connect php to mysql database using local server. Lets create a simple comment box. And I will teach you how to do this on both Mac or windows/Linux. Here is a list of Applications you need before doing some coding. A text editor ( I would recommend Sublime text ) A local server software ( MAMP for mac , Xampp for windows/linux) Now that you have downloaded your local server software, install it and start the servers. If you are on mac follow the screenshot to start up the servers. Bravo ! Your computer is now a server (local though). If you are on windows/Linux follow the similar procedure to start your servers.  Now lets get into some simple coding. Since we are going to make a simple comment box, lets create two files "comment.php"and "comment_post.php" inside htdocs folder. Note : Your def...

Nepal Telecom installs Facebook Cache Server in Nepal

Good news for all Nepalese out there. NTC has just installed facebook Cache server in Nepal with the collaboration with Facebook to bring its cache server to Nepal. This means now facebook can be accessed faster and in cheaper rate from Nepal. It will be applicable for all ISPs s ince all the ISPs of Nepal are the members of NPIX (Internet exchange Nepal).  NTC previously installed Google cache server with the collaboration with Google Inc. making google services like gmail, youtube, google drive, etc faster. In recent years, NTC has become the pioneer telecommunication company of Nepal. What is a cache? A cache (pronounced CASH) is a place to store something temporarily in a computing environment. In computing, active data is often cached to shorten data access times, reduce latency and improve input/output (I/O). Because almost all application workload is dependent upon I/O operations, caching is used to improve application performance. What does a cache ser...

How to read nth line of a text file in C programming using file handling?

C program to read the nth line of a file.  This file handling C program illustrates how to read the nth content of a text file.  Suppose your text filename is "documents.txt" and you want to read only 9th line of that file. Here's a source code to do so. #include <stdio.h> int main () { FILE * file = fopen ( "documents.txt" , "r" ); char line [ 256 ]; int i = 0 ; while ( fgets ( line , sizeof ( line ), file )) { i ++; if ( i == 9 ) { printf ( "%s" , line ); } } fclose ( file ); return 0 ; } Similarly if you want to read only the 1st/2nd/3rd/4th/5th or any other line then just run variable i till your desired line.   For example if i  want to read the 10th line of the same file if ( i == 10 ) { printf ( "%s" , line ); }