Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with: Pieter Kraakman
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with: Pieter Kraakman

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>
  • <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."
  • console.log(
  • ""
  • .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:


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.

Looking For A New Job?

100% of job board revenue is donated to Kiva. Loans that change livesFind out more »

Reader Comments

Just putting it out there... I used splice() today, this would have been handy about 3 hours ago!

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.