Trying to solve this question on Codewars.
I've seen other articles that deal with shuffling / scrambling a string randomly.
But what about scrambling a string according to the values in a given array?
I.e. abcd
given the array [0, 3, 2, 1]
will become acdb
because:
a
moves to index0
b
moves to index3
c
moves to index2
d
moves to index1
My guess is to start out by splitting the string into an array. And then we want to get the index value of the array that's passed into the scramble
function, and push the character at the index value from that array into the new array. And finally join the array:
function scramble(str, arr) {
let newArray = str.split("");
let finalArray = [];
for (let i = 0; i < str.length; i++) {
console.log(newArray);
finalArray.push(newArray.splice(arr[i], 1));
}
return finalArray;
}
console.log(scramble("abcd", [0, 3, 1, 2]));
But the problem with this logic is that .splice()
removes the character from the newArray
every time.
Is there another method that will remove the character at the specified index without modifying the original array?
I don't think slice will work either.