Array.splice() — Interesting and Useful
Let’s code some Javascript
Yesterday I was implementing a React Component to re-arrange items in a list. This simple component should allow users to drag and drop items up and down to change the priority of the items. I was using React DnD and I referred this example React DnD provides. At some point in the sample source code, I was stopped for few minutes to understand following piece of code. Actually, it was doing the array reordering based on the item you want to move and it uses React Immutability Helpers which is an extension of Javascript Array.splice(). So, let’s try to understand this piece of code. We will start from Array.splice().
update(this.state, {
cards: { $splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard]
]
}
})
No big deal. Following is my simple task. Jump to your favourite Javascript editor and give it a try !!!
Following is what we have to do solve this problem.
Using Array.splice()
There are several ways of doing this. First we will solve this using simple Javascript. Following is how Array.splice() is documented:
Simply, splice() method changes the contents of an array by removing existing elements and/or adding new elements.
Three Steps:
- Get the moving item for given index
const movingItem = items[moveFromIndex];
- Remove the moving item from array
items.splice(moveFromIndex, 1);
- Insert moving item to the new position.
items.splice(moveToIndex, 0, movingItem);
Using ImmutableJs
Previous solution solves our original problem. But, it mutates the original array. Let’s see another option. Using ImmutableJs List, we can get a copy of our item list and splice() it without mutating the original. Implementing same three steps I described above. This is nothing else, but a short hand version of our second implementation.
Using immutability-helper Javascript Library
Now we are coming to the explanation we wanted. Understanding the piece of code:
update(this.state, {
cards: { $splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard]
]
}
})
It uses some helper library called immutability-helper which has been written with the intention of simplifying the immutability support Javascript has. If I repeat that intention in their wording:
Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like Clojure. However, we’ve provided a simple immutability helper,
update()
, that makes dealing with this type of data much easier, without fundamentally changing how your data is represented.
Following is how code looks like if I do the same task using splice() operation provided by immutability-helper. I hope now you are in a position to understand the piece of code after comparing with above two sample implementations.