Home > database >  how to solve targetArrayInGivenOrder in JavaScript
how to solve targetArrayInGivenOrder in JavaScript

Time:07-15

Write a function that takes two arrays of integers (nums and index) and returns a target array under the following rules: 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.

Example 1 Input: nums = [0, 1, 2, 3, 4], index = [0, 4, 1, 2, 3] Output: [0, 4, 1, 2, 3]

Example 2 Input: nums = [1, 2, 3, 4, 0], index = [0, 1, 2, 3, 0] Output: [1, 2, 3, 4, 1]

CodePudding user response:

Your example does not match your description. According to your example, you want to insert the nums[index[i]] in your target array's i'th position.

You can do this using Javascript's array.map function like this -

const targetArray = index.map(i => nums[i]);

You may need to add necessary sanity checks as well depending on the contexts.

CodePudding user response:

You can simply achieve this by using Array.forEach() along with Array.splice() method.

Live Demo :

const numsArr = [1, 2, 3, 4, 0];

const indexArr = [0, 1, 2, 3, 0];

let outputArr = [];

numsArr.forEach((elem, index) => {
    outputArr.splice(index, 0, numsArr[indexArr[index]]);
});

console.log(outputArr);

  • Related