Skip to main content
Ben Nadel at InVision In Real Life (IRL) 2019 (Phoenix, AZ) with: David Fraga
Ben Nadel at InVision In Real Life (IRL) 2019 (Phoenix, AZ) with: David Fraga

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

By
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>
<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

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