Leetcode Problem 1389: create target array in the given order

Mariah Morales
2 min readJun 10, 2022

Lo’ and behold!

Another leetcode problem! I’m still pretty terrible at them but I liked this one. Again, iterating has become so second nature to me. I particularly enjoy for loops. But yet again, many of the JavaScript’s built-in methods seem to leave my memory and I once again become stuck! haha.

This problem will simple return a target array that follow some specific rules. Check them out:

Initially target array is empty.

  • From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
  • Repeat the previous step until there are no elements to read in nums and index.

At the end, we simply return the target array.

Here’s an example of a test case:

Seems pretty easy! I know I will of course have to start off with an empty array and iterate over the nums array but what exactly need to go in that block code. NO IDEA!!

Let’s start off what we do know how to do:

I create a let variable equal to an array called targetArray.

Next, I am going to iterate over the two arrays (nums and index) to get each value! Please be advised that although I only iterate visually through the nums array, I am referencing both of them.

There is where I got stuck! I know that I need to insert at index index[i]the value nums[i] in target array but I wasn’t sure how to implement that initially. A quick little Google helped me out. The splice() method is exactly what I needed. Recall that the .splice() method adds and/or removes array elements. At every character, insert the element of numbers at the indexed location from index. Then, we still return the array.

--

--