Skip to main content
Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.

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

By Ben Nadel on

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.

Reader Comments