Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Javascript Array Methods

In this article, we will not cover on fundamental topics such as insertion-deletion or array creation, etc. But we will cover some more advanced array methods essential to work with arrays.

Introduction

Arrays are very important data types of JavaScript. JavaScript provides various array methods which are essential to learn for every concerned programmer, who wants to play with JavaScript.

Array Methods

In JavaScript, Array.prtotype has various array manipulation functions. These functions are available, for any array, as methods. Here we are going to discuss these important methods below:

Join()

The Array.join() method is used to convert all the elements of an array to string and then concatenates them, returning the resulting string. To separate the elements of the resulting string, an optional string can be used. A comma is used to separate the elements, if there is no separator string is used. For example:

Listing 1: Representing the examples of join() method

var temp1 = [1, 2, 3]; 			// Create a new array with 3 elements
temp1.join(); 				//  "1,2,3"
temp1.join(" "); 			//  "1   2   3"
temp1.join(""); 			//  "123"
var temp2 = new Array(10); 		// An empty array with length 10
temp2.join('-')			             //  '---------': a string of 9 hyphens 

This method is a reverse of Array.split() method which brakes an array into pieces to create a new array.

reverse()

when this method is used, it rearrange the elements of an array in reverse order and then return the values in that order. I this process, it will not create any new array with the rearranged elements but instead rearranges them in the original array. For example:

Listing 2: Representing the examples of reverse() method

var temp = [1,2,3];
temp.reverse().join() 		// array is rearranged and temp is now [3,2,1]

sort()

When Array.sort() method is called, it sorts the elements stored in an array and then return the values of sorted arrays. If this method is called without passing any argument, then it temporarily converts the elements into string to compare them with each other and then sort them in alphabetical order:

Listing 3: Representing the example of sort () method

var temp_arr = new Array("banana", "mango", "nuts");
temp_arr.sort();
var sorted_arr = temp_arr.join(", ");		 // sorted_arr == "banana, mango, nuts"

If you want to perform sorting in user defined order rather than alphabetic then, a comparison function must be passed as an argument o the sort(). This function decides the order of its two arguments in sorted array. The comparison function should return a number less than zero in case the first argument should be placed before the second and it should return a value greater than zero if the first argument should be placed after the second one in sorted array. It will return a zero if both of the values are equivalent and comparison is not possible. For example, to sort an array into numerical order:

Listing 4: Representing the other examples of sort() method

var TEMP = [33, 4, 1111, 222];
TEMP.sort(); 					// Alphabetical order: 1111, 222, 33, 4
TEMP.sort(function(a,b) { 			// Numerical order: 4, 33, 222, 1111 
return a-b; 			
});
TEMP.sort(function(a,b) {return b-a}); 	// Reverse numerical order

No names are given to these comparison function expressions because they are used only ones.

concat()

This method is used to concatenate the elements of an existing array with the elements provided by the concat() method as arguments. It create a new array with these concatenated elements. It can concatenate the elements of multiple arrays also. In this case, the participating arrays will not be modified by concat() methods. Some example are given below:

Listing 5: Representing the examples of concat() method

var temp= [1,2,3];
temp.concat(4, 5) 				// Returns [1,2,3,4,5]
temp.concat([4,5]); 				// Returns [1,2,3,4,5]
temp.concat([4,5],[6,7]) 			// Returns [1,2,3,4,5,6,7]
temp.concat(4, [5,[6,7]]) 			// Returns [1,2,3,4,5,[6,7]]

slice()

A Array.slice() method is used to return a sub-array of the specified array. Two arguments are passed into slice method to tell the start and end of the subarra to be returned. The resulting slice has the elements from start argument to one less to the end argument. A negative argument specifies an array element which is relative to the last element in the array. For example if an argument is having a value -3, then it specifies the 3rd element from the last in the array. slice() method does not change the values of the original array. Some examples are given below:

Listing 6: Representing the examples of slice() method

var arr_slice = [1,2,3,4,5];
arr_slice.slice(0,3); 			// Returns [1,2,3]
arr_slice.slice(3); 			// Returns [4,5]
arr_slice.slice(1,-1); 			// Returns [2,3,4]
arr_slice.slice(-3,-2);			 // Returns [3]   

splice()

Array.splice() is a general purpose method which is used to insert new elements in the array, delete the elements from an array or at the same time, perform both operation. Unlike the slice(), this method modifies the value of the array on which it is being applied. The first argument of splice() methods defines the position of the array where the insertion or deletion is to happen. The number of values to be deleted from array is specified by the second argument. All array elements will be removed if the second argument is omitted. For example:

Listing 7: Representing the examples of splice() method

var exp = [1,2,3,4,5,6,7,8];
exp.splice(4); 				// Returns [5,6,7,8]; exp is [1,2,3,4]
exp.splice(1,2); 			// Returns [2,3]; exp is [1,4]
exp.splice(1,1); 			// Returns [4]; exp is [1]

The first two arguments are used to specify the number of items to be deleted. These arguments can be followed by number of other arguments which are inserted into the array, started at the position which is defined by the first argument. For example:

var temp = [1,2,3,4,5];
temp.splice(2,0,'a','b'); 		//  [] is returned; a is [1,2,'a','b',3,4,5]
temp.splice(2,2,[1,2],3); 		//  ['a','b'] is returned; 
//     temp is [1,2,[1,2],3,3,4,5]

push() and pop()

push() and pop() are very popular methods of stack. In JavaScript, these methods can be used with arrays also for insertion and deletion. A push() method inserts one or more new element at the end of an existing element and returns the new length of array. pop() method deletes the last element from an array, and returns the removed value. In this process this method decrements the length of the array. Instead of creating a new array, both of these methods modify the original array. For example, we can implement an stack in JavaScript array using a combination of push() and pop() methods:

Listing 8: Representing the examples of push() and pop() methods

var exam_stack = []; 				// exam_stack: []
exam_stack.push(1,2); 			// exam_stack: [1,2] Returns 2
exam_stack.pop(); 				// exam_stack: [1] Returns 2
exam_stack.push(3); 				// exam_stack: [1,3] Returns 2
exam_stack.pop(); 				// exam_stack: [1] Returns 3
exam_stack.push([4,5]); 			// exam_stack: [1,[4,5]] Returns 2
exam_stack.pop() 				// exam_stack: [1] Returns [4,5]
exam_stack.pop(); 				// exam_stack: [] Returns 1

unshift() and shift()

These methods are much like the push() an pop() method, but they have a major difference. They insert and remove elements from the start rather than the end of an array. unshift() is used to insert one or more new elements to the start of an array by shifting the existing array elements to higher index value, thus creating space for new elements and then return the new length of the array. shift() does opposite to unshift() method. It deletes the first element which cause the shifting of all subsequent values to one less index value so that the vacant space at the start of the array can be occupied. For example:

Listing 9: Representing the examples of unshift() and shift() methods

var temp = []; 					// temp:[]
temp.unshift(1); 				// temp:[1] Returns: 1
temp.unshift(22); 				// temp:[22,1] Returns: 2
temp.shift(); 					// temp:[1] Returns: 22
temp.unshift(3,[4,5]); 				// temp:[3,[4,5],1] Returns: 3
temp.shift(); 					// temp:[[4,5],1] Returns: 3
temp.shift(); 					// temp:[1] Returns: [4,5]
temp.shift(); 					// temp:[] Returns: 1

In the above example, when the unshift() method is supplied with multiple arguments then instead of one by one insertion of values, all arguments are inserted into the arrays all at once. Because of this, order of the elements in the resulting array will be same as they appeared in argument list.

toString() method

A toString() method, when called, converts all the elements of an array to string and then returns a comma separated list of those strings. The output generated by this method, does not include any square brackets or any other delimiter around it. For example:

Listing 10: Representing the examples of toString() method

[4,5,6].toString() 				// returns '4,5,6'
["d", "e", "f"].toString() 			// returns 'd,e,f'
[1, [2,'c']].toString() 				// returns '1,2,c'

Conclusion

JavaScript has various important methods to play with array data type. These methods are used to reduce the complexity of the operations and provide the ease of use to a developer. As a JavaScript developer, you should be familiar with these methods because these methods save lots of time and reduced the complexity of coding.



Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login