This post will discuss how to remove a portion of an array in JavaScript.

There are several ways to remove a portion from an array in JavaScript. We need to remove a subarray of an array that can be specified by a start and an end index. Here are some of the most common functions:

1. Using Array.splice() function

The Array.splice() function removes and/or inserts elements to/from an array, and returns the removed elements as a new array. The original array is modified by this function. To remove a portion of an array, we need to pass the start index and the number of elements to remove as arguments to the splice() function. Here’s an example:

Download  Run Code

2. Using Array.slice() function

The Array.slice() function returns a shallow copy of a portion of an array as a new array, without modifying the original array. To remove a portion of an array, we need to use the slice() function twice: once to get the elements before the slice, and once to get the elements after the slice. Then, we can concatenate the two arrays using the Array.concat() function. Here’s an example:

Download  Run Code

3. Using Array.filter() function

The Array.filter() function creates a new array with all elements that pass the test implemented by the provided function. To use it, we need to pass a function that returns true or false based on some condition. We can then assign the original array to the filtered array to effectively remove the unwanted portion. For instance:

Download  Run Code

4. Using Array.push() function

The Array.push() function adds one or more elements to the end of an array and returns the new length of the array. To remove a portion of an array, we need to iterate over the array and push only the elements that are not in the portion to a new array. Here’s an example:

Download  Run Code

That’s all about removing a portion of an array in JavaScript.