1

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();
4
  • 2
    Sort AFTER you turn the strings into integers Not DURING the conversion. It's trying to sort strings and numbers right now :( It moves the strings around so that you can't convert all of them to integers. Commented Oct 1, 2016 at 21:10
  • Why don't you just do listArray.map(function(num){ return 1*num}).sort(function(a,b) { return a - b; }) Commented Oct 1, 2016 at 21:14
  • 1
    Why would you try to sort inside the loop? Commented Oct 1, 2016 at 21:20
  • why do you think you can't use the map-method? Commented Oct 1, 2016 at 22:43

2 Answers 2

4

You could convert it to number with Number as callback, then sort.

var listArray = ['7', '4', '2', '12', '9'].map(Number);
console.log(listArray);
listArray.sort(function (a,b) { return a-b; });
console.log(listArray);

Or you can first sort, because of the implicit casting to number and then convert the items to number.

var listArray = ['7', '4', '2', '12', '9'];
listArray.sort(function (a,b) { return a-b; });
console.log(listArray);
listArray = listArray.map(Number);
console.log(listArray);

Sign up to request clarification or add additional context in comments.

1 Comment

This worked in the console but didn't jive with the rest of the problem I'm working on. This is a great answer though. Thank you Nina!
2

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();

1 Comment

I can't use the map method and this answer did what I needed for a larger problem I'm working on. Thanks for the illumination!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.