JavaScript Slice

Back to home
Logicmojo - Updated Aug 28, 2021



Javascript Slice

JavaScript has created a big impact as an easy-to-learn programming language for creating dynamic web pages and mobile apps. It works with objects, which are data, and methods, which are processes that you apply to your data, just like any other programming language. Objects can hold a variety of data. An array is a delineated series of things of any kind, simple or constructed of other items, and is one of the most commonly used. To make an array, follow these steps:

const game = ['cricket', 'football', 'baseball','kabaddi']

game is an array of simple things that are strings in this example. You can design a web page with just this one array that can modify its content on the run, showing all names or simply some of them, for example, when the user applies a filter. How does slice accomplish this?

Based on specified circumstances, the slice method generates a duplicate of an array or a portion of it.

It does not manipulate the original array

The slicing conditions contains start and end parameters.

<script>  
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]  
var result=arr.slice(1,2);  
document.writeln(result);  
</script>  



Parameters:

begin: The starting index from which the part will be retrieved is defined by this option. If this parameter is not provided, the method will use 0 as the default start value.

end: The index up to which the section will be extracted is specified by this option (excluding the end index). If this parameter is not specified, the array is extracted until the end, which is the default end value. If the end value is greater than the array's length, the end value is changed to the array's length.

💡 Return value: It creates a new copy of some portion of original array


Use of Slice Method

⮞ Make a duplicate of an array (by dropping both start and end parameters)

⮞ Remove a few components from the beginning and/or end of the rim array

⮞ Remove certain elements


Using Slice in a Function

You can write functions that use many methods to process data. For example, we could make a new array that exclusively contains sweet fruits. We can do this by slicing the array twice and taking the bits before and after the avocado fruit. Consider the possibility of having various fruits, a different number of fruits, or a different position for our savoury fruit. We can cover all scenarios by writing a function with two arguments: array and index, which you can change every time you have a different fruit combination.

function sweet(fruits, index) {
    const beforeAvocado = fruits.slice(0, index); // builds the first subarray
    const afterAvocado = fruits.slice(index + 1); // builds the second subarray
    return [...beforeAvocado, ...afterAvocado]; // puts the arrays together
};
const fruits = ['mango', 'apple', 'avocado','pineapple', 'kiwi'];
const index = 2;
console.log(sweet(fruits, index));



JavaScript slice() With Negative index

Negative start and end indices are also possible in JavaScript. The final element's index is -1, the second last element's index is -2, and so on.

const languages = ["JavaScript", "Python", "C", "C++", "Java"];

// slicing the array from start to second-to-last
let new_arr = languages.slice(0, -1);
console.log(new_arr); // [ 'JavaScript', 'Python', 'C', 'C++' ]

// slicing the array from third-to-last
let new_arr1 = languages.slice(-3);
console.log(new_arr1); // [ 'C', 'C++', 'Java' ]



Differences between slice and splice

The slice method:

SliceSplice
Slice does not mutate the original array.Splice Mutates the original array
Takes two arguments.It has one mandate argument and can take a couple of optional ones to replace elements.
Slice makes a shallow copy of the original array.It mutates the original array by adding or removing the elements.
Returns the copied array.Returns removed elements in a new array.



Conclusion: At this point, you should have a better understanding of JavaScript Slice(). Slice enables you to make your web page's content behave dynamically while also allowing you to re-use the same data in the background.