Search code examples
javascriptarrayssplitsplice

How to insert into an array at a specific index?


I am trying to add a colon in between two numbers I receive from a 4 digit time. However I am receiving an empty string.

const num = 1234
num.toString().split('').splice(-2, 0, ':').join('')
console.log(num)

expected output:

'12:34'

Solution

  • splice operates on the array in place returning an array of deleted elements, or an empty array if none have been deleted. So while you can chain the method in those instances it won't work for your example.

    const num = 1234;
    const arr = num.toString().split('')
    arr.splice(2, 0, ':');
    const str = arr.join('');
    console.log(str)