
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialObjects allows to store key-value pairs. But quite often we need ordered collections. It is not convenient to use an object here, because it provides no methods to manage the order of elements. Also, we can’t insert a new property “between” the existing ones.
There exists a special data structure named Array, to store ordered collections.
There are two ways to create an empty array – Array constructor or square brackets.
Both of them are below.
var arr = new Array();
var arr = [];
In most cases we generally supply an initial set of values, like any Number, String or Boolean.
var wizards = ["Harry", "Hermoine", "Ron"];
Array elements are numbered from zero(0) and not one(1). We can get an element by using square bracket and it’s index.
var wizards = ["Harry", "Hermoine", "Ron"];
console.log(wizards[0]); //Harry
console.log(wizards[1]); //Hermoine
console.log(wizards[2]); //Ron
We can replace an element by just assigning a new element with the square bracket and index notation like below.
var wizards = ["Harry", "Hermoine", "Ron"];
wizards[1] = "Draco";
console.log(wizards); //[ "Harry", "Draco", "Ron" ]
We can also add an element to the end of the array by below. We will add to above wizards array.
wizards[3] = "Ginny";
console.log(wizards); //[ "Harry", "Draco", "Ron", "Ginny" ]
We can also get the total number of elements in an array by the in-built length property. We will check the length of above wizards array.
console.log(wizards.length); //4
We can store any type of an element in an array. It can be string, object, Boolean, number or even a function.
var arr = [ 'Wizard', { name: 'Harry' }, true, function() { console.log('I am a wiz'); } ];
console.log( arr[1].name ); // Harry
arr[3](); // I am a wiz
Array are actually a special type of Object in JavaScript. In JavaScript there are only 7 datatypes – the six primitives and objects.
The typeof array is also object.
var wizards = ["Harry", "Hermoine", "Ron"];
console.log(typeof wizards); //object
Actually, arrays are stored internally by JavaScript, with Number as keys.
var wizards = {0: "Harry", 1: "Hermoine", 2: "Ron"};
console.log(wizards); //Object(3) [ "Harry", "Hermoine", "Ron" ]
There are different loop to iterate over an array.
for loop
One of the earliest ways to cycle over arrays is the traditional for loop.
var wizards = ["Harry", "Hermoine", "Ron"];
for(var i=0; i<wizards.length; i++) {
console.log(wizards[i]);
}
//Harry
//Hermoine
//Ron
for…in loopThe for…in loop is used to iterate over properties of an Objects. In JavaScript, Arrays are also Objects. So, we can use them also to iterate over Arrays.
var wizards = ["Harry", "Hermoine", "Ron"];
for (const index in wizards) {
console.log(wizards[index])
}
//Harry
//Hermoine
//Ron
for…of loopThe for…of loop was introduced in ES6 and is used to iterate over anything that have [Symbol.iterator] property. This includes array, strings and NodeList.
var wizards = ["Harry", "Hermoine", "Ron"];
for (const item of wizards) {
console.log(item)
}
//Harry
//Hermoine
//Ron
Arrays are one of the mostly used data types in JavaScript. So, there are many built-in methods which are useful for different array manipulations.
The method determines whether the passed item is an Array. It returns Boolean – true or false.
var wizards = ["Harry", "Hermoine", "Ron"];
var person = {
firstName:"Harry",
lastName:"Potter",
age:50
}
console.log(Array.isArray(wizards)); //true
console.log(Array.isArray(person)); //false
For Array, the toString method joins the array and returns one string containing each array element separated by commas.
var wizards = ["Harry", "Hermoine", "Ron"];
console.log(wizards.toString()); //Harry,Hermoine,Ron
The pop() method removes the last element from an array and returns that element. This method mutates/changes the original array.
var wizards = ["Harry", "Hermoine", "Ron"];
console.log(wizards.pop()); //Ron
console.log(wizards); //[ "Harry", "Hermoine" ]
The push() method adds an element after the last element of an array and returns the new length of the array. This method mutates/changes the original array.
var wizards = ["Harry", "Hermoine", "Ron"];
console.log(wizards.push('Ginny')); //4
console.log(wizards); //[ "Harry", "Hermoine", "Ron", "Ginny" ]
The shift() method removes the first element of an array and returns that removed element. This method mutates/changes the original array.
var wizards = ["Harry", "Hermoine", "Ron"];
console.log(wizards.shift()); //Harry
console.log(wizards); //["Hermoine", "Ron"]
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. This method mutates/changes the original array.
var wizards = ["Harry", "Hermoine", "Ron"];
console.log(wizards.shift()); //Harry
console.log(wizards); //["Hermoine", "Ron"]
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements. The splice method returns an array with the deleted element(s). This method mutates/changes the original array. Some of the examples are below
var wizards = ["Harry", "Hermoine", "Ron", "Ginny"];
//Remove 0 element from index 2, and insert "Draco"
console.log(wizards.splice(2, 0, "Draco")); //[]
console.log(wizards); //[ "Harry", "Hermoine", "Draco", "Ron", "Ginny" ]
//Remove 1 element from index 3
console.log(wizards.splice(3, 1)); //[ "Ron" ]
console.log(wizards); //[ "Harry", "Hermoine", "Draco", "Ginny" ]
//Remove 1 element from index 2, and insert "Dumbledore"
console.log(wizards.splice(2, 1, "Dumbledore")); // [ "Draco" ]
console.log(wizards); //[ "Harry", "Hermoine", "Dumbledore", "Ginny" ]
//Remove 2 elements from index 1, and insert "Snape", "Dippet", "Pomfrey"
console.log(wizards.splice(1, 2, "Snape", "Dippet", "Pomfrey"));
//[ "Hermoine", "Dumbledore" ]
console.log(wizards); //[ "Harry", "Snape", "Dippet", "Pomfrey", "Ginny" ]
The slice() method returns a portion of an array into new array selected from begin to end. If we don’t mention the end, the end is by default considered to the last element of the array.
var wizards = [ "Harry", "Hermoine", "Dumbledore", "Snape", "Dippet",
"Pomfrey", "Ginny" ];
console.log(wizards.slice(2));
//[ "Dumbledore", "Snape", "Dippet", "Pomfrey", "Ginny" ]
console.log(wizards.slice(2, 4)); //[ "Dumbledore", "Snape" ]
console.log(wizards.slice(1, 5));
//[ "Hermoine", "Dumbledore", "Snape", "Dippet" ]
The original array is not modified, so we have to assign the result in a new array to get the desired output.
var newWizards = wizards.slice(1, 5);
console.log(newWizards); //[ "Hermoine", "Dumbledore", "Snape", "Dippet" ]
console.log(wizards);
//[ "Harry", "Hermoine", "Dumbledore", "Snape", "Dippet", "Pomfrey", "Ginny" ]
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var heroes = ["Harry", "Hermoine", "Ron"];
var teachers = ["Dumbledore", "Snape", "Dippet", "Pomfrey"];
var students = ["Hannah", "Cho", "Vincent"]
var heroesTeachers = heroes.concat(teachers);
var hogwarts = heroes.concat(teachers, students);
console.log(heroesTeachers);
//[ "Harry", "Hermoine", "Ron", "Dumbledore", "Snape", "Dippet", "Pomfrey" ]
console.log(hogwarts);
//[ "Harry", "Hermoine", "Ron", "Dumbledore", "Snape", "Dippet", "Pomfrey", "Hannah", "Cho", "Vincent" ]
console.log(heroes);
//[ "Harry", "Hermoine", "Ron" ]
JavaScript have a sort() method for sorting and some other methods, which are useful to get the specific values out of an array. We will discuss them here.
The sort() method sorts the elements of an array and returns the array, so it changes the original array. The default sort is used to sort string in alphabetical order. So, to use it on numbers we have to modify it a bit.
//String Sort
var hogwarts = [ "Harry", "Hermoine", "Ron", "Dumbledore", "Snape", "Dippet", "Pomfrey", "Hannah", "Cho", "Vincent" ];
hogwarts.sort();
console.log(hogwarts);
//[ "Cho", "Dippet", "Dumbledore", "Hannah", "Harry", "Hermoine", "Pomfrey", "Ron", "Snape", "Vincent" ]
Let see the problem that occurs by applying the sort directly to a number array. In the below example, we want to sort the numbers in the array in ascending order(small to big).
var arr = [1, 30, 4, 21];
arr.sort();
console.log(arr); //[ 1, 21, 30, 4 ]
But as we can see it is not ok. Actually, the sort function first converts all the numbers into its Unicode value and then sort. So, it is not accurate. To fix this we can pass a compare function to the sort. We can pass it as an anonymous function like below. We are covering both ascending and descending case here.
//Ascending order
var arr = [1, 30, 4, 21];
arr.sort(function(a, b) {
return a - b;
});
console.log(arr); //[ 1, 4, 21, 30 ]
//Descending order
var arr = [1, 30, 4, 21];
arr.sort(function(a, b) {
return b - a;
});
console.log(arr); //[ 30, 21, 4, 1 ]
The reverse() method reverses all the elements of an array. So, the first becomes last and so on. It changes or mutate the original array.
var hogwarts = [ "Harry", "Hermoine", "Ron", "Dumbledore", "Snape", "Dippet", "Pomfrey", "Hannah", "Cho", "Vincent" ];
hogwarts.reverse();
console.log(hogwarts);
//[ "Vincent", "Cho", "Hannah", "Pomfrey", "Dippet", "Snape", "Dumbledore", "Ron", "Hermoine", "Harry" ]
We can find the max and min of a number array by using Math.max() and Math.min() respectively. But both these function only takes the arguments passed to it. So, now to pass an array like in the code below, we convert it through apply.
let arr = [20, 6, 29, 12];
console.log(Math.max(20, 6, 29, 12)); // 29
console.log(Math.max.apply(null, arr)); // 29
console.log(Math.min.apply(null, arr)); // 6
JavaScript has a lot of useful and powerful array iteration methods, which are used a lot in real world programming.
All of them have an anonymous callback function passed to it.
This is basically a replacement of the traditional for loop. It executes the provided callback once for each element present in the array. Below is an example which first uses a traditional for loop and then the modern forEach(), to print items from an array.
var heroes = ["Harry", "Hermoine", "Ron"];
for(var i=0 ; i<heroes.length; i++) {
console.log(heroes[i]);
}
//Harry
//Hermoine
//Ron
heroes.forEach(function(hero){
console.log(hero);
});
//Harry
//Hermoine
//Ron
We can also use the shorter ES6 arrow function to further condense the forEach()
heroes.forEach(hero => console.log(hero));
//Harry
//Hermoine
//Ron
The map() method creates a new array, by calling a callback function once for each element of an array. The map() can be considered quite similar to forEach() but the main difference is that it returns a new array without modifying the original array.
The use case for map() are mostly when we pass some array and need to modify each element by a constant term. Like below example, where we add two to every element of the passed array.
let arr = [20, 6, 29, 12];
const map = arr.map(x => x * 2);
console.log(map); //[ 40, 12, 58, 24 ]
console.log(arr); //[20, 6, 29, 12]
The filter() method creates a new array with all the elements that passes the test inside the callback function. It is different then map() in that it can return less elements that passed through it.
In the below example we are finding the small names in array Hogwarts, by checking for each item like wizard.length <= 5. Whichever item gives true for this test comes in our smallNames array.
var hogwarts = [ "Harry", "Hermoine", "Ron", "Dumbledore", "Snape", "Dippet", "Pomfrey", "Hannah", "Cho", "Vincent"];
var smallNames = hogwarts.filter(wizard => wizard.length <= 5);
console.log(smallNames); //[ "Harry", "Ron", "Snape", "Cho" ]
Notice that we are using the shorter arrow function above. The same can be written without arrow function as below.
var smallNames = hogwarts.filter(function(wizard){
return wizard.length <= 5;
});
console.log(smallNames); //[ "Harry", "Ron", "Snape", "Cho" ]
The reduce() method is a bit different then all the other array method. The method executes a reducer function on each member of the array resulting in a single output value. It also doesn’t change the original array.
In its most basic form, we are using it to sum all the elements of an array.
let arr = [20, 6, 29, 12];
const sumArr = arr.reduce((acc, curr) => acc + curr);
console.log(sumArr); //67
console.log(arr); //[20, 6, 29, 12]
Here we are passing two arguments to the callback function.
Accumulator(acc)
The accumulator accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).
currentValue(curr)
The current element being processed in the array.
initialValue(Optional)
Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used.
Reduce function iterate through the array for each element of the array and uses the accumulator to store the value from the last iteration. The above reduce function doesn’t have a initialValue, so first time it will add 20+6 and keep 26 in acc. Next iteration will add 26+29 and keep 55 in acc. And then the final iteration will add 55+12 and return 67.
Let’s add an initialValue to reduce and with it the accumulator will start with 10.
let arr = [20, 6, 29, 12];
const sumArr = arr.reduce(function(acc, curr) {
return acc + curr;
},10);
console.log(sumArr); //77
console.log(arr); //[20, 6, 29, 12]
The every() method returns true, only if all the elements passes the test in the callback function.
let arr = [20, 6, 29, 12];
//Check if every element is greater than equal to 6
console.log(arr.every(item => item >= 6)); //true
let heroes = ["Harry", "Hermoine", "Ron"];
//Check if every element of array have length greater than 5
console.log(heroes.every(function(hero){
return hero.length > 5
})); //false
The some() method returns true, even if one element passes the test in the callback function.
let arr = [20, 6, 29, 12];
//Check if some element is less than 6
console.log(arr.some(item => item < 6)); //false
let heroes = ["Harry", "Hermoine", "Ron"];
//Check if some element of array have length greater than 5
console.log(heroes.some(function(hero){
return hero.length > 5
})); //true
The indexOf() method returns the first index at which a passed element can be found in the array, or -1 if it is not present.
let arr = [20, 6, 29, 12];
console.log(arr.indexOf(55)); //-1
let heroes = ["Harry", "Hermoine", "Ron", "Dumbledore", "Hermoine","Snape"];
console.log(heroes.indexOf("Hermoine")); //1
The lastIndexOf() method returns the last index at which a passed element can be found in the array, or -1 if it is not present.
let arr = [20, 6, 29, 12];
console.log(arr.lastIndexOf(55)); //-1
let heroes = ["Harry", "Hermoine", "Ron", "Dumbledore", "Hermoine","Snape"];
console.log(heroes.lastIndexOf("Hermoine")); //4
The find() method returns the value of the first element in the array that satisfies the provided testing function in the callback. Otherwise undefined is returned.
let arr = [5, 20, 6, 29, 12];
console.log(arr.find(function(itm){
return itm > 6
})); //20
let heroes = ["Harry", "Hermoine", "Ron", "Dumbledore", "Hermoine","Snape"];
console.log(heroes.find(hero => hero.length < 3)); //undefined
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function in the callback. Otherwise -1 is returned.
let arr = [5, 20, 6, 29, 12];
console.log(arr.findIndex(function(itm){
return itm > 6
})); //1
let heroes = ["Harry", "Hermoine", "Ron", "Dumbledore", "Hermoine","Snape"];
console.log(heroes.findIndex(hero => hero.length < 3)); //-1