4 回答
TA贡献1807条经验 获得超9个赞
假设所有元素都是唯一的:
let originalArray = ['a','b','c','d','e','f','g'];
let itemsToBeMoved = ['c','f','e'];
let newIndexToBeMoved = 4;
// find the value of the element the marks the insertion point
let insertBefore = originalArray[newIndexToBeMoved];
// in original sequence order, check for presence in the removal
// list, *and* remove them from the original array
let moved = [];
for (let i = 0; i < originalArray.length; ) {
let value = originalArray[i];
if (itemsToBeMoved.indexOf(value) >= 0) {
moved.push(value);
originalArray.splice(i, 1);
} else {
++i;
}
}
// find the new index of the insertion point
let insertionIndex = originalArray.indexOf(insertBefore);
if (insertionIndex < 0) {
insertionIndex = originalArray.length;
}
// and add the elements back in
originalArray.splice(insertionIndex, 0, ...moved);
console.log(originalArray);
TA贡献1876条经验 获得超7个赞
这可以通过多种方式解决,但这里简要介绍一下可以做什么:
首先,您可以为要移动的项目创建一个“当前”地图(基于源数组中的位置)
现在,过滤数组,删除项目,但跟踪它们是否存在
将(排序的)当前过滤掉的值拼接到所需位置的更改数组中(基于源数组中的索引)
const move = (arr, items, index) => {
const present = new Map(items.map(item => [item, arr.indexOf(item)]));
const altered = arr.filter(item => !present.has(item));
altered.splice(arr.indexOf(arr[index - 1]), 0, ...([...present.entries()]
.filter(([k, v]) => v !== -1)
.sort(([, k1], [, k2]) => k1 - k2)
.map(([k, v]) => k)));
return altered;
}
const moved = move(['a','b','c','d','e','f','g'], ['c','f','e'], 4);
console.log(moved);
.as-console-wrapper { top: 0; max-height: 100% !important; }
TA贡献1815条经验 获得超10个赞
typescript
这是一种使用and来实现的方法generics
。它不会改变数组,速度非常快。
将物品移动到新位置时,总会有一系列物品受到移动的影响。受影响是指在该范围内,所有项目都必须移动。我计算范围的最小值/最大值,该范围之外的任何项目都将简单地从旧数组复制到新数组。
然后,根据项目是在数组中向上移动还是向下移动,我将每个项目从旧数组复制到新数组,同时考虑到移动的偏移量。
export const arrayMove = <ItemType>({
arr,
from,
to,
movedItemsCount = 1,
}: {
arr: ItemType[]
from: number
to: number
movedItemsCount?: number
}) => {
if (from === to) return arr
const minAffected = Math.min(from, to)
const maxAffected = Math.max(to, from + movedItemsCount - 1)
const pushedItemsCount = maxAffected - minAffected + 1 - movedItemsCount
const newArr: ItemType[] = []
newArr.length = arr.length
for (let i = 0; i < arr.length; i++) {
if (i < minAffected || i > maxAffected) {
// When i is outside the affected range,
// items are identical in new and old arrays
newArr[i] = arr[i]
} else {
// Moving items down
if (to > from) {
if (i < to - movedItemsCount + 1) {
// Write pushed items
newArr[i] = arr[i + movedItemsCount]
} else {
// Write moved items
newArr[i] = arr[i - pushedItemsCount]
}
} else {
// Moving items up
if (i < to + movedItemsCount) {
// Write moved items
newArr[i] = arr[i + pushedItemsCount]
} else {
// Write pushed items
newArr[i] = arr[i - movedItemsCount]
}
}
}
}
return newArr
}
TA贡献2080条经验 获得超4个赞
尝试这个:
const originalArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const itemsToBeMoved = ['c', 'f', 'e'];
const newIndexToBeMoved = 4;
originalArray.splice(newIndexToBeMoved, 0, itemsToBeMoved)
console.log(originalArray.flat())
添加回答
举报