var sourceArray = ["wombat", "koala", "emu", "kookaburra"] var newArray = sourceArray.splice(1, 1); // Should return 'koala' as the single item in the new array console.log(JSON.stringify(newArray)); // ["koala"] console.log(JSON.stringify(sourceArray)); // ["wombat", "emu", "kookaburra"].
var newArray = sourceArray.pureSplice(start, deleteCount);
deleteCount: How many elements you want to drop from the array.
Running the same code below, substituting .pureSplice() for .splice(), returns a new array with the specified elements removed. Crucially, the source array is not changed:
var sourceArray = ["wombat", "koala", "emu", "kookaburra"] var newArray = sourceArray.pureSplice(1, 1); // Should remove 'koala' from returned newArray console.log(JSON.stringify(newArray)); // ["wombat", "emu", "kookaburra"] console.log(JSON.stringify(sourceArray)); // ["wombat", "koala", "emu", "kookaburra"]
How to use/install
Install from npm with:
npm install --save array.prototype.puresplice
Require or import like so for ES6:
or like this for CommonJS:
The index.js is implemented in UMD format, so should also work for AMD/RequireJS, but I've not tested that. You can also add it as a script tag.
npm install to update the dev dependencies, basically the Babel command line tool and its dependences.
The source code is in the src/getsourcearray.js file, and is in ES2015 (aka ES6) format. Run
npm run build to have Babel transpile the code to es5 format to the project's main file, i.e. index.js in the root.
Tests are built with mocha + chai. Run with
Tests check that a new array can be returned from a source array with:
- A single element removed in the returned array
- The source array remaining unchanged.