How To Create A Target Array in the Order Given in Javascript

Christa Gammage
Oct 29, 2020

Given two arrays of equal length, nums and index, return a new array with the elements of nums left to right positioned at the index of index left to right. Repeat this until there are no elements left in either array.

Example input: nums = [0,1,2,3,4]; index = [0,1,2,2,1]. The returned target array would look like: [0,4,1,3,2].

So let’s jump in!

First, we’ll begin by declaring our targetArray which will be returned.

Next, we’ll create a for loop that will loop through each element in both arrays. It will end when i is equal to the length of our arrays. Since they’re of equal length, it doesn’t matter which is referenced in the for loop.

Let’s declare our index variable and nums variable so that we can use it in our splice method. The .splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Next, let’s write our .splice() method. We’ll be inserting one numsNum element at the index of indexNum.

Lastly, we’ll need to return targetArray after it has finished looping through all of the elements.

Good luck with your algorithm studies!

--

--