# 1389. Create Target Array in the Given Order ## 題目概要 給定兩個陣列 nums, index,同時遍歷nums 和 index,將 `nums[i]` 賦予給 `arr[index[i]]` ,最後回傳 arr。 ``` Example 1: Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2] Example 2: Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] Explanation: nums index target 1 0 [1] 2 1 [1,2] 3 2 [1,2,3] 4 3 [1,2,3,4] 0 0 [0,1,2,3,4] Example 3: Input: nums = [1], inde ``` ## 解題技巧 - 這題可以用 splice 簡單的解決。`Array.splice(start, deleteCount, item)`,第一個參數為起始位置,第二個參數為要刪除幾個元素,第三個參數為要插入的值。 ## 程式碼 ```javascript= /** * @param {number[]} nums * @param {number[]} index * @return {number[]} */ var createTargetArray = function(nums, index) { let result = [] nums.map((e, i) => { result.splice(index[i], 0, e); // 從 index[i] 開始刪除 0 個元素並插入 nums[i] }) return result }; ``` ![](https://i.imgur.com/KbJOKfP.png)