Objects 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 loop
The 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 loop
The 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
I have learned many things from this article. It is beneficial for me. Thank you!
Nice example for beginners.. I m a beginner so this is very helpful for me ... so plz give this type of beginners example..
This is a great introduction to variables in JavaScript! As a beginner to JavaScript, I found this guide very helpful in understanding the basics of variables and how they are used in JavaScript.
Thanks for sharing the information, it is very helpful, I hope to get more such beautiful blogs from you.
You have shared great information with me i appreciate your work!
Build various types of web applications,command-line application,etc....
Introduction: Angular (What is Angular?)Angular was formerly introdu...
Leave a Reply
Your email address will not be published. Required fields are marked *