Efficient Array Manipulation Splice Removal in JavaScript
Explore our JavaScript category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different JavaScript functions that can be used in various projects according to their specific requirements.
This JavaScript code demonstrates the use of the splice method to remove elements from an array.
<script>
</script>
// Create an array called splArray with three elements
var splArray = ["St1", "St2", "st3"]; // Log the original array to the console
console.log(splArray); // Use the splice method to remove elements from index 0 up to (but not including) index 2
splArray.splice(0, 2); // Log the modified array to the console
console.log(splArray);</script>
Let's go step by step:
- The initial array splArray contains three elements: "St1", "St2", and "st3".
- The console.log(splArray) statement outputs the original array to the console.
- The splice(0, 2) method is used on the array. It starts at index 0 and removes 2 elements. In this case, it removes "St1" and "St2".
- After the splice operation, the console.log(splArray) statement outputs the modified array, which now contains only the remaining element, "st3".
["St1", "St2", "st3"] // Original array
["st3"] // Modified array after using splice
["st3"] // Modified array after using splice