JavaScript Extract Elements From Array

JavaScript Extract Elements From Array

javaScript extract element/data/value from array; In this tutorial, you will learn how to how to extract elements from array in javascript using array slice() method.

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.

AuthorAdmin

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, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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