A slice() function return extracted part of array from the specified index and returns new extracted array without affecting an existing array. A array index starts from 0 as first element.
1 <array_object>.slice(<start_position>, <end_position>)
array_object : An array object from which we want to extract sub array
start_position : A starting position from where we want to extract array, if negative value provided as starting position, it start counting from the end of array
end_position : A end position till that position we want to extract array, if negative value provided as starting position, it start counting from the end of array
1 let array = [10, 20, 30, 40, 50, 60, 70];
2
3 let extracted = array.slice(2, 5);
4
5 let extracted = array.slice(-5, -1);
6
7 let extracted = array.slice(10, 3);
Note : If starting position is greater than ending position, a slice() function returns empty array.
In the above example, we have define string object with initial value. In the first example, array extracted from index value 2 to 5, which will return [30, 40, 50]. In the second example, string extracted from -5 to -1 when index value specified negative, it will start from right side, meaning from end of string. It will start from 5 elements from end of array till 1 elements from end.
In the last example, the start index is greater than end index which is invalid, hence it will return empty array.
Extract elements from array
Extract elements from array
1 let array = ["hello", "from", "IOGyan", "array", "Tutorial"];
2
3 let res = array.slice(1, 4);
4
5 console.log("Original array :", array);
6 console.log("An extracted array :", res);
In the above example, an array is define an intialized with string literals. A slice() method called by specifying an index position. It creates slice from index position 1 till index position 3. It does not includes end index element. A resulting array is assigned to the variable and printed.
1 Original array : [ 'hello', 'from', 'IOGyan', 'array', 'Tutorial' ]
2 An extracted array : [ 'from', 'IOGyan', 'array' ]
User define slice function
User define slice function
1 function slice(arr, beg, end) {
2 let s = beg < 0 ? 0 : beg;
3 let len = arr.length;
4 let e = end > len || end < 0 ? arr.length : end;
5 let res = [];
6
7 for(i = s; i < e; i++) {
8 res[res.length] = arr[i];
9 }
10 return res;
11 }
12
13
14 let array = [10, 20, 30, 40, 50];
15 let res = slice(array, 1, 4);
16
17 console.log("Original array :", array);
18 console.log("An extracted array :", res);
In the above example, an array is define and initialized with number values. A slice() function define that accepts three parameters, an array, starting position and ending position. A function determine the starting and ending position and create slice of an array. A resulting slice is returned from function that assigned to the variable and printed.
1 Original array : [ 10, 20, 30, 40, 50 ]
2 An extracted array : [ 20, 30, 40 ]
Related options for your search