Skip to content

JavaScript array slice method example | Select Array elements

  • by

JavaScript array slice method is used to get the portion of Array. It selects the elements to start and ends at given parameter values, but excludes the end argument.

Note: The original Array will remains unchanged.

Syntax

array.slice(start, end)

Parameter Values

The first element has an index of 0.

  • start:- Integer value, where to start the selection. (Optional)
  • end:- Integer value, where to end the selection. (Optional)

Return value

It returns the selected elements in new array object.

Examples of slice method in javascript

Let’s see some example of slice() method used in array.

Start and End Argument

Select elements from an array in JS. In the examples using the start and end index position.

<!DOCTYPE html>
<html>
  <head>
    <script>
    	var alpha = ["A", "B", "C", "D", "E"];
		var beta = alpha.slice(1, 3)
		// output in console 
		console.log(beta);

    </script>
  </head>   

</html>

Output:

JavaScript array slice method example

Pass negative arguments

Select elements using negative values in slice() method.

<!DOCTYPE html>
<html>
  <head>
    <script>
    	var alpha = ["A", "B", "C", "D", "E"];
		var beta = alpha.slice(-3, -1);
		// output in console 
		console.log(beta);

    </script>
  </head>   

</html>

Output:

Select Array elements

slice() extracts the entire array

If you don’t pass any argument, then the JS array slice method will extract the same array. (copy the array)

<!DOCTYPE html>
<html>
  <head>
    <script>
    	var alpha = ["A", "B", "C", "D", "E"];
		var s = alpha.slice();
		// output in console 
		console.log(s);

    </script>
  </head>   

</html>

Output: [“A”, “B”, “C”, “D”, “E”]

Q: How to remove an element from array javascript?

Answer: The splice() method adds/removes items to/from an array, and returns the removed item(s).

See below example of remove elements from array in JS.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);        // Removes the first element of fruits

Do comment if you know more about it and want to contribute, or have any doubts and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading