Spliced - A Version Of Splice() That Returns The Original Array In JavaScript
This isn't really a blog post so much as it is a stream-of-consciousness; but, sometimes I think it would be nice if JavaScript had a version of splice() that would return the mutated array rather than the collection of deleted values. To demonstrate, I've augmented the Array.prototype to include the method, spliced(). This simply proxies the core splice() method and returns the original object reference:
<!doctype html>
<html>
<head>
<title>
Spliced in Array Prototype To Return Original Array Reference
</title>
</head>
<body>
<h1>
Spliced in Array Prototype To Return Original Array Reference
</h1>
<script type="text/javascript">
// This does the same exact thing as .splice(); but, it returns the original
// array reference rather than the collection of items that were deleted.
Array.prototype.spliced = function() {
// Returns the array of values deleted from array.
Array.prototype.splice.apply( this, arguments );
// Return current (mutated) array array reference.
return( this );
};
// -------------------------------------------------- //
// -------------------------------------------------- //
// Logs the value, "0.a.b.1.2.3.4.x.y.5"
console.log(
"0.1.2.3.4.5"
.split( "." )
.spliced( 1, 0, "a", "b" )
.spliced( -1, 0, "x", "y" )
.join( "." )
);
</script>
</body>
</html>
When I run the above code, I get the following console output:
0.a.b.1.2.3.4.x.y.5
As you can see, I'm calling .spliced() twice in a row in the middle of a method-chain. I can only do this because the original array reference is being returned. The native .splice() method would have returned the deleted values which would have caused the subsequent methods to act on the wrong array reference.
I'm not saying this should replace .splice(); rather, work in parallel with it. Anyway, just a random thought at the end of a long day.
Want to use code from this post? Check out the license.
Reader Comments
Just putting it out there... I used splice() today, this would have been handy about 3 hours ago!
@Joey,
That's awesome to hear. Maybe I'm not so crazy after all :D