Search code examples
javascriptarraysfor-loopparseint

Converting array of strings into numbers


I'm trying to convert this array of strings (which are all integers) into an array of numbers. For some reason when I use the following function it doesn't change the first string in the array to a number. I'm not sure why. Can someone explain that to me?

var listArray = ['7', '4', '2', '12', '9'];
function makeNums(){
  for(var i = 0; i < listArray.length; i++){
    listArray[i] = parseInt(listArray[i], 10);
    listArray.sort(function(a,b) { return a - b; });
    console.log(listArray[i]);  
  }

}

makeNums();

Solution

  • Move the sorting outside of the iteration. That way it won't sort until the array has been processed. Try running the code snippet below:

    var listArray = ['7', '4', '2', '12', '9'];
    function makeNums(){
      for(var i = 0; i < listArray.length; i++){
        listArray[i] = parseInt(listArray[i], 10); 
      }
      listArray.sort(function(a,b) { return a - b; });
      console.log(listArray); 
    }
    
    makeNums();