C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Array splice() methodThe JavaScript array splice() method is used to add/remove the elements to/from the existing array. It returns the removed elements from an array. The splice() method also modifies the original array. SyntaxThe splice() method is represented by the following syntax: array.splice(start,delete,element1,element2,?,elementn) Parameterstart - It represents the index from where the method start to extract the elements. delete - It is optional. It represents the number of elements to be removed. element1,element2,...,elementn - It is optional. It represent the elements to be inserted. ReturnA new array containing the removed elements. JavaScript Array splice() method exampleHere, we will understand splice() method through various examples. Example 1Let's see an example to add an element to the existing array without removing other elements. <script> var arr=["Monday","Tuesday","Thursday","Friday"]; var result=arr.splice(2,0,"Wednesday") document.writeln(arr); </script> Output: Monday,Tuesday,Wednesday,Thursday,Friday Example 2Let's see an example to add an element to the existing array while removing other elements. <script> var arr=["Monday","Tuesday","Saturday","Sunday","Thursday","Friday"]; var result=arr.splice(2,2,"Wednesday") document.writeln("Updated array: "+arr+"<br>"); document.writeln("Removed element: "+result); </script> Output: Updated array: Monday,Tuesday,Wednesday,Thursday,Friday Removed element: Saturday,Sunday Example 3Let's see an example to add two elements to the existing array while removing one element. <script> var arr=["Monday","Tuesday","Sunday","Friday"]; var result=arr.splice(2,1,"Wednesday","Thursday"); document.writeln("Updated array: "+arr+"<br>"); document.writeln("Removed element: "+result); </script> Output: Updated array: Monday,Tuesday,Wednesday,Thursday,Friday Removed element: Sunday Example 4Let's see an example to remove the elements from the existing array. <script> var arr=["Monday","Tuesday","Saturday","Sunday","Thursday","Friday"]; var result=arr.splice(2); document.writeln("Updated array: "+arr+"<br>"); document.writeln("Removed element: "+result); </script> Output: Updated array: Monday,Tuesday Removed element: Saturday,Sunday,Thursday,Friday
Next TopicJavaScript Array
|