Reorder string using array / javascript indexes

I am stuck with this challenge, any help would be great.

'Create a function that takes both a string and an array of numbers as arguments. Reorder the letters in the string so that they are in the order indicated by the index numbers. Return the string "remixed". Examples

remix ("abcd", [0, 3, 1, 2]) ➞ "acdb" '

My attempt is

function remix(str, arr) { var arr2 = []; for (var i=0; i<str.length; i++){ arr2.splice(arr[i], 0, str[i]); } return arr2.join(""); 

}

This will solve some, but not all tests. EG. ("abcd", [0, 3, 1, 2]) = "acdb", but some are not. EG. "responsibility", [0, 6, 8, 11, 10, 7, 13, 5, 3, 2, 4, 12, 1, 9]) should be - "rtibliensyopis" my "rteislbpoyinsi"

+5
source share
3 answers

You can use the value arr[i] as the target index for the actual letter.

 function remix(str, arr) { var result = [], i; for (i = 0; i < str.length; i++) { result[arr[i]] = str[i]; } return result.join(''); } console.log(remix("abcd", [0, 3, 1, 2])); // "acdb" console.log(remix("responsibility", [0, 6, 8, 11, 10, 7, 13, 5, 3, 2, 4, 12, 1, 9])) // "rtibliensyopis" 
+2
source
 function myFunction(text, nums){ var arr = []; for(var num in nums){ arr.push(text.charAt(nums[num])); } return arr; 

};

I think this should work.

0
source

Edited answer - at first misinterpreted the question.

You can use Array.prototype.reduce to fill the positions in the new array with letters from str based on the target positions from arr :

 const remix = ( str, arr ) => ( arr.reduce( (acc, target, idx) => { acc[target] = str[idx]; return acc; }, []) ).join(''); 

or reduce the array of letters in str to an array:

 const remix = ( str, arr ) => ( [...str].reduce( (acc, letter, idx) => { acc[arr[idx]] = letter; return acc; }, []) ).join(''); 
0
source

Source: https://habr.com/ru/post/1272740/


All Articles