[JavaScript]Replace elements in Array with one line of code

In this post, I would like to share very simple way to replace an element or elements in an Array with JavaScript.

We often need to replace an element or elements in an Array. There are no explicitly named method, “replace”, in JavaScript. Fortunately, there is “splice” method that seems to be made for the purpose.

The “splice” method does not only replacing an element or elements, but also removing or adding an element or elements in the middle of an Array. In fact, removing and adding elements at a certain position in array are “replacing”. It is safe to say that the method, “splice”, adds and removes an element or elements at specific position of an array, which also means “replacing the elements in the array”.

The method, “splice”, takes 3 or more parameters of which one is required and the others are optional.

The first parameter indicates the starting index. It means where to start replacing. The second parameter indicates how many elements from the starting index will be replaced. The parameters after the 2nd indicates what will be replaced with.

Rather than documentation-like verbal explaination, I would like go through with simple examples.

Mission1: replace single element “Mar” at index 1 with “Feb”!

It changes the original array, months, to [“Jan”, “Feb”, “Mar”, “April”] as expected.

Mission2: replace multiple elements

The method, “splice”, is capable of replacing more than one element by setting the second and third paramters.

It changes the original array to [“Jan”, “Feb”, “Feb2”, “April”] as expected.

If you change the second paramter to 3, you get to replace 3 elements from the starting index.

Mission3: replace multiple elements with the spread operator!

Being a bit more creative, I tried to replace elements using the spread operator of other array.

It changes the original array to [“Jan”, “Feb”, “Feb2”, “Feb4”] as expected.

What does the method returns?

Whenever I implement Array method in JavaScript, I think it is very important to know if the method changes the original array and what the method returns.

We have checked “splice” changes the original array. Then what does it return? Let me test it with the simple code below.

It turns out that it returns an array with removed elements from the original array.

This is it.

Thank you for reading my post. I hope this post helped you.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Steve Kim

Steve Kim

A Certified Public Accountant / Hobbyist-programmer-but-dead-serious-specializing JavaScript, ReactJS, NextJS and AWS.