Move An Array Item To A New Index
Move an item to a new index with two splice calls in place, or rebuild with slices immutably; same-slot moves and past-end targets stay predictable.
Code
const list = ["alpha", "beta", "gamma", "delta", "epsilon"];
// 就地移动:splice 先取出再插回目标位
function moveTo(arr, from, to) {
const [item] = arr.splice(from, 1);
arr.splice(to, 0, item);
return arr;
}
console.log(`in place: ${moveTo([...list], 4, 0).join(",")}`);
// 不可变移动:切片拼接,原数组保持不动
function moveToImmutable(arr, from, to) {
const item = arr[from];
const rest = [...arr.slice(0, from), ...arr.slice(from + 1)];
return [...rest.slice(0, to), item, ...rest.slice(to)];
}
console.log(`immutable: ${moveToImmutable(list, 0, 3).join(",")}`);
console.log(`original: ${list.join(",")}`);
// 同位移动与越界目标:目标 index 超出范围时结果仍可预期
console.log(`same slot: ${moveToImmutable(list, 2, 2).join(",")}`);
console.log(`past end: ${moveToImmutable(list, 1, 10).join(",")}`);
How the snippet works
Everything happens inside the functions moveTo and moveToImmutable.
The input arr is mutated in place — callers that need the original must pass a copy. It builds and returns a fresh value rather than reusing its inputs.
Watch out for
- Zero third-party dependencies — the runtime provides every API used here.
arris mutated in place — the value you pass will not be the same afterward.
Putting it to use
The primary signature is function moveTo(arr, from, to)
Running the file prints labeled results such as in place: $, immutable: $, original: $ — each operation’s effect is visible in the output.
Core lines
return [...rest.slice(0, to), item, ...rest.slice(to)];
Interactive Tools for This Topic
FAQ
- Does `moveTo` modify its input?
- Yes — `arr` is mutated in place, and the return value is a new object rather than the mutated input. Pass a copy if the caller needs the original preserved.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `moveTo`, `moveToImmutable` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.