JavaScript Higher Order Functions and Arrays
Posted By : Jayant Singh Parmar | 15-Aug-2018
Hi everyone, in this blog, I am going to do something different that may not be enough for filling visually into the browser but it will really
Alright like I said this is not going to be like a project where we build something in the UI. We are just going to use the browser's console for our output. So if you want to follow along, all you have to do is create the following files.
- index.html: Basic head, body tags
and a h1 and a link to our main javascript file. - main.js: Our main javascript file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>JavaScript higher order functions and arrays</h1>
<h3>Note:
<span style="color: red">Open your browser's console to see the output</span>
</h3>
<script src="main.js"></script>
</body>
</html>
In our main.js file we two arrays, one is "companies" which has just a bunch of objects and the second one is a simple array with numbers called "ages".
const companies = [
{ name: "Company One", category: "Finance", start: 1981, end: 2004 },
{ name: "Company Two", category: "Retail", start: 1992, end: 2008 },
{ name: "Company Three", category: "Auto", start: 1999, end: 2007 },
{ name: "Company Four", category: "Retail", start: 1989, end: 2010 },
{ name: "Company Five", category: "Technology", start: 2009, end: 2014 },
{ name: "Company Six", category: "Finance", start: 1987, end: 2010 },
{ name: "Company Seven", category: "Auto", start: 1986, end: 1996 },
{ name: "Company Eight", category: "Technology", start: 2011, end: 2016 },
{ name: "Company Nine", category: "Retail", start: 1981, end: 1989 }
];
const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];
The methods we are going to look at are as follows.
- forEach( ): It is actually
a easy and a better way to loop through an array rather than using a forloop . Itdosn't return anything but it's a much nicer and elegant way to loop through the data. I will also be comparing it with a basic for loop so you can see the difference. I have also attached the screenshots of output obtainedform the browser's console.So let's take the following example.// Basic for loop console.log('----------Output of for loop-----------'); for (let index = 0; index < companies.length; index++) { console.log('Companies', companies[index]); }
Now let's use
forEach loop.// 1. forEach(): Loops thorugh an array // ES5 Version console.log('----------Output of forEach()-----------'); companies.forEach(function(company){ console.log('Companies', company); }); // ES6 Version companies.forEach((company) => { console.log('Companies', company); });
- filter( ): What filter does it actually allows us to filter the things out from an array. So let's say we want all the ages that are greater than or equal to 21, from the ages array.
// 2. filter(): Filter things out of an array // Get 21 or older console.log('----------Output of filter()-----------'); // ES5 Version const canDrink = ages.filter(function(age){ if (age >= 21) { return true } }); console.log('21 or older', canDrink); //ES6 Version const canDrink = ages.filter(age => age >= 21); console.log('21 or older', canDrink);
Let's take another example in which we will filter all the retail companies from the companies array.
// Fiter the retail companies // ES5 Version const retailCompanies = companies.filter(function (company) { if (company.category === 'Retail') return true; }); console.log('Retail Companies', retailCompanies); // ES6 Version const retailCompanies = companies.filter(company => company.category === 'Retail'); console.log('Retail Companies', retailCompanies);
Now let's filter the companies that started in the 80s
// Get companies that started in 80s const eightiesCompanies = companies.filter(company => (company.start >= 1980 && company.start < 1990)); console.log('Companies started in 80s', eightiesCompanies);
Let's take another
exmple and filter out the companies that lasted for 10 years or more// Get companies that lasted for 10 years or more const lastedTenYears = companies.filter(company => (company.end - company.start >= 10)); console.log('Companies lasted for 10 years or more', lastedTenYears);
- map( ): Map works a little bit differently, instead of just filtering things out it creates a new array from the current array. So let's just grab all of the company names and put them into their own array.
// 3. map(): Creates a new array from the current array // console.log('----------Output of map()-----------'); // Create a new array of company names // ES5 Version const companyNames = companies.map(function(company){ return company.name; }); console.log('Company Names', companyNames); // ES6 Version const companyNames = companies.map(company => company.name); console.log('Company Names', companyNames);
Now let's create an array of strings and each string will be formatted like "Company Name [Start Year - End Year]"
// Create an array of template strings like "Comapany Name [Start Year - End Year]" const testMap = companies.map(company => `${company.name} [${company.start} - ${company.end}]`); console.log('Template String', testMap);
Let's do one more example with
map , let's use the ages array. So what we will do here is take each one and get the square root of each number// Create an array of sqaure roots of all ages const agesSquareRoots = ages.map(age => Math.sqrt(age)); console.log('Square roots of ages', agesSquareRoots);
- sort( ): It works similar to rest of these functions. So here we will sort the companies by start year.
// 4. sort(): Sorts an array // console.log('----------Output of sort()-----------'); // Sort the companies by the start year // ES5 Version const sortedCompanies = companies.sort(function(c1, c2){ if (c1.start > c2.start) { return 1; } else { return -1; } }); console.log('Companies sort by the start year', sortedCompanies); // ES6 Version const sortedCompanies = companies.sort((a, b) => (a.start > b.start ? 1: -1)); console.log('Companies sorted by the start year', sortedCompanies);
Let's do one more example with sort( ), let's sort the ages so we just have simple numbers array and we have to sort it from lowest to highest.
// Sort ages const sortedAges = ages.sort((a, b) => a - b); console.log('Sorted Ages', sortedAges);
- reduce( ): It can be used for a lot of things and it can get quite complicated but I am going to keep it simple. So let's add all of the ages together from the ages array. First I will do it with a for loop so you can see the difference.
// 5. reduce(): console.log('----------Output of reduce()-----------'); // Get sum of all ages // Using basic for loop let ageSum = 0; for (let index = 0; index < ages.length; index++) { ageSum += ages[index]; } console.log('Sum of ages = ', ageSum); // ES5 Version const ageSum = ages.reduce(function(total, age) { return total + age; }, 0); console.log('Sum of ages = ', ageSum); // ES6 Version const ageSum = ages.reduce((total, age) => total + age, 0); console.log('Sum of ages = ', ageSum);
Let's do another example with reduce( ), let's get total years for all companies
// Get total years for all comapnies // ES5 Version const totalYears = companies.reduce(function(total, company) { return total + (company.end - company.start); }, 0); console.log('Total years for all companies', totalYears); // ES6 Version const totalYears = companies.reduce((total, company) => total + (company.end - company.start), 0); console.log('Total years for all companies = ', totalYears);
Now you can use any of these functions together to do certain things. I am going to give you an
// Combine Methods
console.log('----------Output of combined methods-----------');
const combined = ages
.map(age => age * 2) // multiply all ages by 2
.filter(age => age >= 40) // filter all ages greater than or equal to 40
.sort((a, b) => a - b) // sort all ages in ascending order
.reduce((a, b) => a + b, 0); // get sum of all ages
console.log(combined);
Alright that is going to be it, what I would suggest for you is to maybe create your
You can download the source code here
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Jayant Singh Parmar
Jayant has more than 5+ years of industry experience as a frontend developer. He has good knowledge of technologies like Angular, reactJS, HTML, CSS, javascript etc. He is proficient in building complex UI designs, implentation of complex logics on frontend, API integrations, development and deployments and have been part of successfully delivering services on various client projects like Virgin Media, Hp1t and Jabburr He is a quick learner and keen to learn new technologies.