猿问

如何将数组中的多个项目移动到数组中的不同索引?

我有一个包含 7 个项目的数组。我想以与原始数组中相同的顺序将一些项目移动到不同的索引。到目前为止,我已将代码片段粘贴到我尝试过的任何内容上。


let originalArray = ['a','b','c','d','e','f','g'];


let itemsToBeMoved = ['c','f','e'];


let newIndexToBeMoved = 4;


//expected result is ['a','b','d','c','e','f','g'];


let movableItemsIndex = [];

movableItemsIndex.push(originalArray.indexOf('c'));

movableItemsIndex.push(originalArray.indexOf('f'));

movableItemsIndex.push(originalArray.indexOf('e'));


//To be Moved items has to be sorted as in originalArray

movableItemsIndex.sort();


let itemsToBeMovedSorted = [originalArray[movableItemsIndex[0]],originalArray[movableItemsIndex[1]],originalArray[movableItemsIndex[2]]];


//Removing items before inserting to items to new position

while(movableItemsIndex.length) {

    originalArray.splice(movableItemsIndex.pop(), 1);

}

let newUpdatedArray = [...originalArray],j=0;

for(let i = newIndexToBeMoved ;i < originalArray.length ; i++){

  newUpdatedArray[i] = itemsToBeMovedSorted[j];

  j++;

}

console.log(newUpdatedArray);


慕的地10843
浏览 110回答 4
4回答

函数式编程

假设所有元素都是唯一的: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 pointlet insertBefore = originalArray[newIndexToBeMoved];// in original sequence order, check for presence in the removal// list, *and* remove them from the original arraylet moved = [];for (let i = 0; i < originalArray.length; ) {&nbsp; &nbsp; let value = originalArray[i];&nbsp; &nbsp; if (itemsToBeMoved.indexOf(value) >= 0) {&nbsp; &nbsp; &nbsp; &nbsp; moved.push(value);&nbsp; &nbsp; &nbsp; &nbsp; originalArray.splice(i, 1);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; ++i;&nbsp; &nbsp; }}// find the new index of the insertion pointlet insertionIndex = originalArray.indexOf(insertBefore);if (insertionIndex < 0) {&nbsp; &nbsp; insertionIndex = originalArray.length;}// and add the elements back inoriginalArray.splice(insertionIndex, 0, ...moved);console.log(originalArray);

幕布斯6054654

这可以通过多种方式解决,但这里简要介绍一下可以做什么:首先,您可以为要移动的项目创建一个“当前”地图(基于源数组中的位置)现在,过滤数组,删除项目,但跟踪它们是否存在将(排序的)当前过滤掉的值拼接到所需位置的更改数组中(基于源数组中的索引)const move = (arr, items, index) => {&nbsp; const present = new Map(items.map(item => [item, arr.indexOf(item)]));&nbsp; const altered = arr.filter(item => !present.has(item));&nbsp; altered.splice(arr.indexOf(arr[index - 1]), 0, ...([...present.entries()]&nbsp; &nbsp; .filter(([k, v]) => v !== -1)&nbsp; &nbsp; .sort(([, k1], [, k2]) => k1 - k2)&nbsp; &nbsp; .map(([k, v]) => k)));&nbsp; 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; }

动漫人物

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}

犯罪嫌疑人X

尝试这个: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())
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答