javascriptarrayssplicespread

Can you use a shallow copied variable in splice?


Apologies for the terrible title I didn't know how else to word it. this is a kata im trying to complete in codeWars. Drone Fly-by. basically the lamps parameter will be a string of 'x' characters and starting from zeroth index replace them with 'o' based on the length of the drone.

function flyBy(lamps, drone){
  let arr = [...lamps];
  let dl = drone.length;

  console.log(arr,dl,drone)
  // shows ['x', 'x', 'x', 'x', 'x', 'x' ] 5 '====T'
  
  let answer = arr.splice(0, dl, 'o').join('');
  
    console.log(answer)
  //shows xxxxx
  

As far as I am aware the first parameter of splice is the starting index, the second is the number of elements to delete and third (or more) what to insert. I have tried reading through Mozilla and I'm lost as to why this doesn't work. I appreciate this doesn't solve the kata but I was expecting ox. Is it anything to do with the arr variable using the spread operator? my understanding is that this has created an array literal shallow copy of the original string which I can apply splice and join('') it back into a string.

I appreciate there will be far more efficient and cleaner ways of solving the kata but I'm more interested in the reasons why this doesn't return ox.


Solution

  • From the docs:

    Return value

    An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

    splice returns what was removed. In this case, you removed 5 x's, and that's why you get xxxxx in return. You should call splice, and then join on arr:

    arr.splice(0, dl, 'o');
    
    let answer = arr.join('');
    
    console.log(answer); // 'ox'