Search code examples
javascriptarraystypescriptreplacesplice

Getting empty array on applying splice. How to fix it?


Here I want to add word at the last 4 letter before the x length. So i converted the string to array. Applied split. But when i tried to splice. Getting empty string on adding the second argument to the splice. Looking for help.

let x = "abcdefgh";
console.log(x);
console.log(x.length);
let y = x.split('');
console.log(y);
let len = (y.length - 4);
console.log(len);
console.log(y.splice(len));
console.log(y.splice(len, 0, "test"));


Solution

  • Your problem is understanding what Array#splice() returns

    Per Array#splice() MDN docs

    Returns: 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.


    So do the splice first then log the whole array to see results

    let x = "abcdefgh";
    
    let y = x.split('');
    
    let len = (y.length - 4);
    y.splice(len, 0, "test");
    
    console.log(y);