
JavaScript Array Methods: how to use map and reduce
Methods are property names that we can assign to a functions. They can be invoked at any time just by using the name to execute a function. Array objects also have methods and properties that allow us modify or query them onto the object.
In JavaScript,array methods make it easy to manage and organize data in a convenient way. Today, we will be diving intotwo popular array methods:map()
andreduce
. These methods provide a modified version of an array and make arrays even more convenient.
Today, we will learn:
- JavaScript arrays refresher
- What are array methods?
- JavaScript
map()
method map()
examples and uses- JavaScript
reduce
method reduce
examples and uses- Using
reduce
andmap()
together - What to learn next
JavaScript arrays refresher
When creating variables in JavaScript, it can be tricky to access a range of values. Similarly, creating objects requires you to create key names for all the data, which can lead to clutter.Arrays are the solution. Thisdata structure manages ordered data in one interface.
Arrays are a collection ofindividual values separated by a comma, each with its own index/location. Arrays are objects with methods and properties used for managing data items in an orderly fashion.
They are list-like data structures that group data together, making them accessible through numerical indices.
In JavaScript, arrays are easy to declare. Below, we create an array of fruit types and store them in an orderly fashion.
varfruit=["Orange","Apple","Banana"];
Arrays in JavaScript havespecial features that make them particularly useful, including:
- They are dynamic
- They can be sparse or dense
- They are mutable
- They have methods and properties to make organization convenient
What are array methods?
Array objects havemethods andproperties that allows us to modify or query them onto an object. These make it much easier to manage, access, and organize data. This way, we don't have to create custom objects.
Theproperty of an array is an attribute of that array, such as length or memory size. They are usually static values that can be used to change a particular quality of the object.prototype
andlength
are common properties.
Methods of an array are actions that we can apply to an array. These are similar to properties but are of the type function.push()
andpop()
are common array methods that allow us to add or remove elements.
Refresher: Functions are a set of instructions that carry out a task. They allow us to reuse code anywhere in the program.
Array methods help make your programs far more convenient and useful. Next, we'll look at two unique JavaScript array methods that make arrays even more convenient:map()
andreduce
.
JavaScriptmap()
method
Themap()
method is used to get a modified version of the array or a reduced value using callback functions.map()
applies a function to each array element and creates a new array of the returned values.
The syntax of the method is as follows:
array.map(function(currentValue,index,arr),thisValue)
Themap()
method accepts two parameters:
function(currentValue, index, arr)
: This is a required parameter that runs on each element of array. It contains three parameters:currentValue
,index
andarr
.thisValue
: This parameter is optional. It holds the value of passed to the function.
The map method will take a function invoked for each element in the array as in input. The function that is be passed is given arguments by the map method in the following order.
functioncallbackfn(value:any,index:number,array:any[])
For each element, thecallbackfn
will be passed with the value of the element as the first argument, followed by the index of the element as the second argument. Lastly the array itself as the third argument. Thiscallbackfn
function takes between 0 to 3 arguments.
Finally, a new array with all the returned values from thecallbackfn
function will be returned by the map method. Check out an example below.
vararr=[10,20,30,40,50];// initialise an array and assign to arrvararr1=arr.map(a=>a*2);// double the element in the arrayconsole.log("arr:",arr);// print original arrayconsole.log("doubled array:",arr1);// print doubled array
Note: You can see that the map method maps the arrow function to each element and returns a new array. The original array remains unchanged.
map()
examples and uses
There are many uses ofmap()
in your JavaScript code.Let's break down the most common ones.
Generic use ofmap()
Below, our code shows how to use this method on aString
to generate an array of bytes in ASCII encoding.
letmap=Array.prototype.mapleta=map.call('Hello World',function(x){returnx.charCodeAt(0)})
Mapping an array of numbers to an array of their square roots
Below, our code takes an array of numbers and creates a new array with the square roots of each number.
letnumbers=[3,25,100]letroots=numbers.map(function(num){returnMath.sqrt(num)})
Mapping an array of numbers with a function containing an argument
Below, our code shows howmap()
can be used alongside a a function that has one argument. The argument will be assigned automatically from each element of the array.
letnumbers=[3,25,100]letdoubles=numbers.map(function(num){returnnum*2})
Note: Sincemap()
builds a new array, you shouldnot use this method if:
- You are not using the array that is returned
- You are not returning any value from the callback
Keep the learning going.
Learn how to build with JavaScript without scrubbing through videos or documentation. Educative's text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.
JavaScriptreduce
method
Thereduce
method reduces the array to a single value from left to right. This method leaves the original array unchanged.
The syntax of the method is as follows:
arr.reduce(<function>);
Thereduce
method takes a function invoked for each element in the array. It uses the reduced value of the previous element to the next. The reduce method gives arguments to the passed function in the following order:
functioncallbackfn(prev:any,curr:any,index:number,array:number[])
For each element, thecallbackfn
will be passed with the previouscallbackfn
function’s return value as the first argument, and the value of the element as the second argument.
This is followed by the index of the element as the third argument. Lastly, the array itself is taken as the fourth argument.
Thecallbackfn
function returns a value passed onto thecallbackfn
function for the next element. If the array has only one value, that value is returned. For an empty array, an error is thrown.
Let’s learn more aboutreduce
with an example below.
vararr=[10,20,30,40,50];// initialise an array and assign to arrvarval=arr.reduce((prev,curr)=>prev+curr);// reduce element to sumconsole.log("arr:",arr);// print original arrayconsole.log("reduced val:",val);// print element returned by reduce
We can see here that the arrow function takes the previous valueprev
and adds it to the value iterated in the arraycurr
. The reduce method sums the entire array.
Note: We can use the
reduceRight
method to apply the reduce method in the opposite direction.
reduce
examples and uses
There are many uses ofreduce
in your JavaScript code.Let's break down the most common ones.
Sum the values of an array
We can usereduce
to sum all the values of an array in an easy way.
letsum=[0,1,2,3].reduce(function(accumulator,currentValue){returnaccumulator+currentValue},0)
Flatten an array of arrays
letflattened=[[0,1],[2,3],[4,5]].reduce(function(accumulator,currentValue){returnaccumulator.concat(currentValue)},[])
Group objects by a property
letpeople=[{name:'Matt',age:25},{name:'Asma',age:23},{name:'Cami',age:29}];functiongroupBy(objectArray,property){returnobjectArray.reduce(function(acc,obj){letkey=obj[property]if(!acc[key]){acc[key]=[]}acc[key].push(obj)returnacc},{})}letgroupedPeople=groupBy(people,'age')
Usingreduce
andmap()
together
Now let's learn how an example of how we can use the two methods together to make certain tasks easier. Often, we need to count array elements that satisfy a certain condition. Here's how it's done:
- Map the array into an array of zeros and ones.
- Reduce the array of zeros and ones into the sum.
The final output is a count of elements that satisfy a given condition.
vararr=['Hello',1,true,NaN,'Bye'];// initialise an array of elementsvarcountArr=arr.map(ele=>typeofele==='string'?1:0);// map to 0 and 1varsum=countArr.reduce((prev,curr)=>prev+curr);// reduce for sumconsole.log("arr:",arr);// print original arrayconsole.log("array from map:",countArr);// print array returned from map methodconsole.log("number of Strings:",sum);// print number of strings
On line 2, we apply map to get an array of ones and zeroes. Each satisfying element has one value. In line 3, we use reduce to find the sum of the array. This means we have a count of ones. then, using combo, we find the element count in the array assigned toarr
where the element is a string.
Note: We can also use these methods together to find the number of elements in a two-dimensional array.
What to learn next
Congrats! You've now taken a deep dive into JavaScript'smap()
andreduce
array methods. These will improve your code a lot. There's still more to learn when it comes to array methods. Next, you should check out the following:
some()
every()
flat()
filter()
forEach()
flatMap()
To get started with these array methods and get some practice withmap()
andreduce
, check out Educative's courseJavaScript in Detail: From Beginner to Advanced. In this project-based course you will dissect every part of JavaScript from beginning to advanced. You will be tasked with four hands-on projects and formal tests to solidifying your learning. By the end, you'll be a proficient JavaScript developer.
Happy learning!
Continue reading about JavaScript
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse