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. Rearrange the letters in the string to be in the order specified by the index numbers. Return the "remixed" string. Examples
remix("abcd", [0, 3, 1, 2]) ➞ "acdb"'
My attempt -
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 of the tests. EG. ("abcd", [0, 3, 1, 2]) = "acdb" but some do not. EG. "responsibility", [0, 6, 8, 11, 10, 7, 13, 5, 3, 2, 4, 12, 1, 9]) should be - "rtibliensyopis" mine is "rteislbpoyinsi"
You could use the value of arr[i]
as 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With