How to splice an array without mutating the original Array?


In JavaScript, we can use the splice() method to splice an array. The splice() method inserts or deletes single or multiple elements from the array. We can pass the starting index as the first parameter of the splice() method, from which we can insert or delete the elements. It takes the number of elements to delete from the array as a second parameter and array values as the third parameter to insert into the array.

This tutorial will teach us to splice an array without mutating the original array. Mutating the original array means making changes to the array. Whenever we use the original array with the splice() method, it either inserts or removes some elements from the original array. So, we will make a clone of the array and use the splice() method with cloned array to keep the original array the same.

Syntax

Users can follow the syntax below to use the array.splice() method.

  let results = array.splice(startIndex, count, element1, element2, element3, ... , elementN);

Parameters

  • startIndex − It is the first index to insert or remove elements from the array.

  • Count − It is a number of elements to replace in the array. If we pass 0 as a value of count, it inserts the elements at startIndex.

  • Element1, element2, …, element − It is new array elements to start replacing or inserting from the start index.

Now, we will see different approaches to splicing an array without mutating the original array.

Use the spread operator to splice an array without mutating the original array

The spread operator allows us to make a clone of the array. We can create a clone of the original array using the spread operator, and after that, we can use the splice() method with the cloned array to splice an array without mutating the original array.

Syntax

Users can follow the syntax below to use the spread operator to splice an array without mutating the original array.

let splicedArray = [...array].splice(0, 3);

In the above syntax, the array is an original array with that we have used the spread operator to make its clone and used the splice() method with the cloned array.

Example 1

In the example below, we have created an array of various strings. After that, we used the array with the spread operator in the ‘[]’ braces to make its clone and used the splice() method.

We have passed the 0 as a start index in the splice() method and three as the total number of elements to remove from the array.

<html>
   <body>
      <h3> Using the <i> spread operator </i> to splice an array without mutating the original array. </h3>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById('output');
         let array = ["C", "Java", "CPP", "JavaScript", "TypeScript", "html", "HTML", "NodeJs", "ReactJs", "NextJs"];
         let splicedArray = [...array].splice(0, 3);
         output.innerHTML += "Orignal array after the splicing: " + array + "<br>";
         output.innerHTML += "Spliced array after the splicing:" + splicedArray + "<br>";
      </script>
   </body>
</html>

Use the filter() method to splice an array without mutating the original array

We can create a new array by filtering elements from the original array. The splice() method extracts the total count's elements from the start index. So, we can filter out total count elements from the start index using the filter() method.

Syntax

Users can follow the syntax below to use the filter() method to splice an array without mutating the original array.

let splicedArray = array.filter((ele, ind) => {
   if (ind >= startIndex && ind < counts + startIndex) {
      return true;
   }
      return false;
})

In the above syntax, we have filtered the array elements from the startIndex to count + startIndex.

Example 2

In the example below, we have an array and use the filter() method with the array. Users can see how the filter() method extracts the total count of elements from the startIndex.

Also, it remains the same when we use the filter() method with the original array.

<html>
   <body>
      <h3> Using the <i> filter() method </i> to splice an array without mutating the original array. </h3>
      <div id = "output"> </div>
      <button onclick = "spliceArray()"> Splice an array </button>
      <script>
         let output = document.getElementById('output');
            function spliceArray() {
               let startIndex = 5;
               let counts = 3;
               let array = ["C", "Java", "Cpp", "JavaScript", "TypeScript", "html", "HTML", "NodeJs", "ReactJs", "NextJs"];
            
            let splicedArray = array.filter((ele, ind) => {
               if (ind >= startIndex && ind < counts + startIndex) {
                  return true;
               }
                  return false;
            })
            output.innerHTML += "Orignal array after the splicing is " + array + "<br>";
            output.innerHTML += "Spliced array after the splicing is " + splicedArray + "<br>";
         }
      </script>
   </body>
</html>

Use the slice() method to splice an array without mutating the original array

The slice() method extracts the array elements, and here we will use the made copy of the array. When we pass the 0 as the first parameter of the slice() method while using it with the array, it makes a clone of the array.

After that, we can use the splice() method to splice an array without mutating the original array.

Syntax

Users can follow the syntax below to use the slice() and splice() methods to splice an array without mutating the original array.

let clonedArray = array.slice(0);
let splicedArray = clonedArray.splice(start, end);

In the above syntax, first, we used the slice() method to make a clone of the array, and after that, we used the splice() method to splice() an array.

Example 3

The below example contains the array of numbers with multiple numeric values. After that, clonedArray contains the clone of the original array.

Next, we used the splice() method with the clonedArray, and users can check the original array is the same.

<html>
   <body>
      <h3> Using the <i> slice() </i> method to splice an array without mutating the original array </h3>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById('output');
         let array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
         let clonedArray = array.slice(0);
         let splicedArray = clonedArray.splice(1, 6);
         output.innerHTML += "Orignal array after the splicing: " + array + "<br>";
         output.innerHTML += "Spliced array after the splicing: " + splicedArray + "<br>";
      </script>
   </body>
</html>

Updated on: 07-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements