Search code examples
javascriptarrayssubstr

Substr on an array element if not empty


Hei, I have an array containing some empty strings and some strings with content.

I want to slice down the first 5 letters of those which are not empty strings, and put them into a new array. I also want to keep the empty ones.

example:

myArray = [ "","","123456789","","",""];
var newArray = ["","","12345","","",""]

I tried with for loop with if inside if the myArray[i] is empty then don't do substr(), but I get an error that it is not a function.

I actually don't need to put it into a new array, I just want to put the myArray(i).subsrt(5) value into a splice(), but then I get the error:

VM750:82 Uncaught TypeError: Cannot read property 'substr' of undefined


Solution

  • ES6 with array.map

    myArray = [ "","","123456789","","",""];
    var newArray = myArray.map((s) => s.substr(0, 5))