配列内の要素を指定位置へ移動させる
D&Dで要素を並び替えした時にデータを保存してあるcollectionに対してよく使うのでメモ
function moveAt(array, index, at) {
if (index === at || index > array.length -1 || at > array.length - 1) {
return array;
}
const value = array[index];
const tail = array.slice(index + 1);
array.splice(index);
Array.prototype.push.apply(array, tail);
array.splice(at, 0, value);
return array;
}
実行結果
function fruitsMove(index, at) {
const fruits = ['apple', 'banana', 'grape', 'orange', 'peach'];
moveAt(fruits, index, at);
console.log(fruits);
}
// 'apple' を fruits[1] へ移動
fruitsMove(0, 1) // => ["banana", "apple", "grape", "orange", "peach"];
// 'peach' を fruits[1] へ移動
fruitsMove(4, 1); // => ["apple", "peach", "banana", "grape", "orange"]
// 'apple' を fruits[4] へ移動
fruitsMove(0, 4); // => ["banana", "grape", "orange", "peach", "apple"]
// 'peach' を fruits[0] へ移動
fruitsMove(4, 0); // => ["peach", "apple", "banana", "grape", "orange"]