For more tips like this, sign up to the weekly newsletter!
Preserve the original index before filtering or sorting
When you need to display a list of elements, usually you need their indices to know which one to update on user action.
For example, for an Array of strings, when a user clicks to remove one, the function gets the index:
const todos = [...];
const removeTodo = (index) => {
todos.splice(index, 1);
...
}
This works well, as you know the index when you display the elements:
todos
.map((todo, index) => {
...
removeTodo(index);
...
})
But if you sort or filter them, the indices no longer match the ones in the original array:
todos
.sortBy(...)
.map((todo, index) => {
// The index no longer matches the one in the todos!
})
In this case, save the original index and pass that as well as the element:
todos
.map((todo, index) => ({todo, originalIndex: index}))
.sortBy(...)
.map(({todo, originalIndex}) => {
...
removeTodo(originalIndex);
...
})