Skip to main content
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with: Tim Cunningham
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with: Tim Cunningham ( @TimCunningham71 )

Spliced - A Version Of Splice() That Returns The Original Array In JavaScript

Published in Comments (2)

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>
		Spliced in Array Prototype To Return Original Array Reference

		Spliced in Array Prototype To Return Original Array Reference

	<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."
				.split( "." )
					.spliced( 1, 0, "a", "b" )
					.spliced( -1, 0, "x", "y" )
					.join( "." )



When I run the above code, I get the following console output:


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

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel