Search code examples
javascriptexcel-addins

How to transform all strings to numbers in a nested array, except actual strings in Javascript?


I am trying to transform all values in a 2D array from strings to numbers, except values that are actually strings (within the Javascript Excel Add-in API)

Example:

[["1000"],["3.2"],["banana"]]

to

[[1000],[3.2],["banana]]

"1000" -> 1000
"3.2" -> 3.2
"banana" -> "banana"

Solution

  • This function will help you solve the problem:

    var values = ['1000','3.2','banana'];
    
    function stringToNumber(arrayOfValues) {
      for (var i = 0; i < arrayOfValues.length; i++) {
        if (typeof arrayOfValues[i] != 'string' || isNaN(arrayOfValues[i])) {
          continue;
        }
        arrayOfValues[i] = +arrayOfValues[i];  // + before a string converts it to number
      }
    }
    

    Update:

    In the comment below, you wrote you receive a nested array from Excel, so I wrote a recursive function for you:

    var arrayOfArrays = [
      ['1000','3.2','banana'], 
      ['2','value','1820','just a word', true], 
      [20]
    ]; 
    
    var values = ['1000','3.2','banana']; 
    
    function stringToNumber(arrayOfValues) { 
      for (var i = 0; i < arrayOfValues.length; i++) { 
        if (typeof arrayOfValues[i] == 'object') {
          stringToNumber(arrayOfValues[i]); continue;
        }
        if (typeof arrayOfValues[i] != 'string' || isNaN(arrayOfValues[i])) {
          continue;
        }
        arrayOfValues[i] = +arrayOfValues[i]; // + before a string converts it to number
      }
    }
    

    Try it out!