Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change order of a string using an array indexes/ Javascript

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"

like image 663
jmac Avatar asked Oct 29 '22 00:10

jmac


1 Answers

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"
like image 124
Nina Scholz Avatar answered Nov 13 '22 03:11

Nina Scholz