AniUI Academy

Move an item to a new position

mediumArrays & Objects+250 XPPractice

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 unchanged

What 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 -1 is 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.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.