JavaScript Array Slice() | Extract Elements From Array

JavaScript Array Slice() | Extract Elements From Array

In this tutorial, you will learn all about the JavaScript array slice() method and how to use it.

By using js array slice() method, you perform different tasks like, you can copy the array, create a new array from given array, without changing the original array.

JavaScript Array slice() method

Javascript array slice() method extracts a part of an array from a given array and returns a new array.

The following syntax represents the slice() method:

slice(begin, end);

Note that, the js array slice() method takes two optional parameters.

Here,

  • The begin is a position where to start the extraction.
  • The end  is a position where to end the extraction.

Note that, about js array slice() method:

  • If begin is undefined, slice begins from the index 0.
  • If end is omitted, slice extracts through the end of the sequence (arr.length).

Let’s take a look example of js array.slice() method:

Example 1: Clone an array

The following example shows how to clone an array using the js array slice() method:

var nums = [1,2,3,4,5];
var res = nums.slice();

In this example, the res array contains all the elements of the nums array.

Example 2: Copy a portion of an array

The following example shows how to copy the portion of an array without changing the original array using the slice() method.

See the following example:

var lang = ['php','java','c','c#','.net', 'python'];
var res = lang.slice(0,4);
console.log(res); // ["php", "java", "c", "c#"]

The res array contains the first 4 elements of the lang array. The original array lang remains entire.

Conclusion

In this tutorial, you have learned JavaScript array slice() method and how to use it.

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Codeigniter, Vue JS, Angular JS, React Js, WordPress and Bootstrap from a starting stage.

Leave a Reply

Your email address will not be published. Required fields are marked *