Array slice() Method

The Array slice() method returns a portion of an array as a new array. The syntax for this method is


			array.slice(start,end); 
			
start
Optional. The index at which extraction is to begin. If start is negative, selection is done from the end of an array. slice(-3) will extract the last three elements of the array it is applied upon. If start is unspecified, it starts from the index 0.
end
Optional. Index upto which extraction is to be done, but excluding it. slice(1,3) extracts the elements with indices 1, 2 but not 3. Negative end indicates offset from the last element, but excludes it.

We consider an array named os consisting of four elements


			var os = ["Debian", "Fedora", "openSUSE", "Ubuntu"];
			

Applying the slice() method to os with the first parameter as 1 for the starting index and the second parameter as 3, and assigning the returned object to the variable extract


			var extract = os.slice(1,3);
			

we get an array consisting of the elements from index 1 to 2, but excluding 3


			["Fedora", "openSUSE"];
			

We next move on to negative indices. Consider the start index with -3 value, which starts from the third element from the end of the array, and the end index with -1 value, which is the last element of the array


			var extract = os.slice(-3,-1);
			

The variable extract contains the following elements


			["Fedora", "openSUSE"];
			

If the end parameter is omitted, and only the start parameter is given, say -3, extraction is done from the last third element till the end of the array


			var extract = os.slice(-3);
			

and the variable extract contains the array


			["Fedora", "openSUSE", "Ubuntu"];
			

The extract the last element of the array os


			var extract = os.slice(-1);