Search code examples
javascriptarraysfor-loopsplice

how do i return a spliced array using multiple indexes from a different array


dft=["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"];
ans=[4, 6, 12, -1];  
for(x=0;x<ans-1;x++){
dft.splice(ans[x],0,"-");}
return dft;

I am trying to return an array that has "-" placed into the dft array using the indexes in the ans array except the -1 index.

result im getting is ["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"]

this is the codepen i am working on


Solution

  • Firstly, it's not doing anything because your for loop end condition should be checking the loop parameter x against the length of the ans array, i.e. x < ans.length -1. Secondly, since splice is changing the array, your ans indices will be incorrect after you insert the first hyphen, so you should do it in reverse order like so:

    dft = ["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"];
    ans = [4, 6, 12, -1];
    
    for (x = ans.length - 2; x >= 0; x--) {
        dft.splice(ans[x], 0, "-");
    }
    
    console.log(dft);

    We start at the end of the array, which would be ans.length - 1, except you want to skip the last element, so we start at ans.length - 2. Remember though that this assumes that the last element should be ignored.