我有一个包含 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);
函数式编程
幕布斯6054654
动漫人物
犯罪嫌疑人X
相关分类