Move an item to a new position
Drag a task from the bottom of a list to the top and something has to compute the new order. Doing it with splice on the state array directly is how you get a list that reorders in memory but never re-renders.
Implement move(items, from, to). Take the item at index from, remove it, and re-insert it so that it ends up at index to in the returned array. Both indices may be negative, counting back from the end, so -1 refers to the last item. Return a new array; the input is never modified. If either index, after resolving a negative value, falls outside the range of valid positions in the array, return an unchanged shallow copy of the input.
Arguments
itemsArray- The input list. Not modified.
fromnumber- Index of the item to move. Negative values count back from the end.
tonumber- Target index for the moved item. Negative values count back from the end.
Returns
Array — A new array with the item relocated. An out-of-range index returns an unchanged shallow copy.
Examples
move(["a", "b", "c", "d"], 0, 2);
// ["b", "c", "a", "d"]move(["a", "b", "c"], -1, 0); // ["c", "a", "b"] — negative indices from the end
move(["a", "b"], 5, 0); // ["a", "b"] — out-of-range returns a copy unchangedWhat it has to do
- Return a new array with the item relocated, leaving the other items in order.
- Treat negative indices as counting back from the end, so
-1is the last item. - Return an unchanged shallow copy when either resolved index is out of range.
- Handle moving both forwards and backwards through the array.
- Do not mutate the input array.
Stuck? The javascript course covers everything this challenge needs.
- 1.moves an item forwards
- 2.moves an item backwards
- 3.resolves negative indices from the end
- 4.returns an unchanged copy for an out-of-range index
- 5.does not mutate the input
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.