DEV Community

danielarmbruster0314
danielarmbruster0314

Posted on

Well splice seems interesting

So me and my peer discovered in our boot camp lab today that If you use the .splice() method on an array and want to use it to make a copy with an additional element at the end of the array ( exp. Arr.splice(start, deletecount, new element added).)
You kind of have to know the length of the array because it adds the new element to the left indexs of the specified starting point so .splice(-1,0,”newstring”)will add the new string an index before the final element in the array and not at the end of the array. Wild, just wild. Any comments to expand my understanding of this method is more than welcome.

Top comments (5)

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

I'd argue that the best way to insert at the end of an array is push and at the start is unshift. splice is very handy when working with rearranging lists, drag and drop and the like as it can be applied anywhere within the list using the index of the insert before item.

Negative indexing for "last items" is very helpful, and also works with slice to make an array from a source array. In the latest Javascript there is also the at function which allows you to look up individual items using negative indexing.

Collapse
 
joas8211 profile image
Jesse Sivonen

There's better ways to clone and append to an array than splice. Splice actually mutates the original array and I use it mainly to remove an element from an array. Could you explain why you want to use splice? For the sake of experimenting? With ES6 you can initiate a new array and use spread to create such an array.

const originalArray = [1, 2, 3];
const newArray = [...originalArray, 4, 5, 6];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
danielarmbruster0314 profile image
danielarmbruster0314

Yeah I was just trying to better understand it’s functionality and this seemed like a small enough experiment to test the potential implementation. Definitely agree that your example using the spread operator is a much more practical approach.

Collapse
 
curiousdev profile image
CuriousDev

For "cloning" objects JSON.stringify and JSON.parse can be used. Just wanted to mention it, but it does not work for all cases!

Collapse