0

I have a two dimensional array that I need to sort numerically. Here is a sample of the array:

   [0]    [1]
    3     320
    55B   250
    26    100
    55A   260
    56    310
    89    420

I need to order numerically by the [0] values. The values are stored as strings. I have figured how to sort arrays alphabetically and numerically but I can't figure out how to order this array because of the occasional A and B.

5
  • Do I understand it right, the array is like this: [ [3, 320], ["55B", 250], 26, 100] ] and not [ [3, "55B", 26], [320, 250, 100] ] ? Commented Nov 9, 2011 at 19:30
  • Could you maybe describe more specifically how you want the values sorted? It all seems a little arbitrary right now. What are the constraints? In other words, will letters ALWAYS occur in the third position from the left? Stuff like that. Commented Nov 9, 2011 at 19:31
  • possible duplicate of Sort a 2D array by the second value Commented Nov 9, 2011 at 19:33
  • As I understand, he know how to sort, but he dont know how to sort numbers with 'A' and 'B' at the end... Commented Nov 9, 2011 at 19:37
  • @AdamJurczyk that's basically it... Commented Nov 9, 2011 at 19:55

2 Answers 2

4

The parseInt method will ignore any string characters after the number, removing the A's and B's.

arr.sort(function(rowA, rowB){
    var a = parseInt(rowA[0], 10);
    var b = parseInt(rowB[0], 10);

    if (a > b)
        return 1;
    else if (a < b)
        return -1;
    return 0;
});
Sign up to request clarification or add additional context in comments.

1 Comment

arr.sort(function (a, b) { return parseInt(a[0], 10) - parseInt(b[0], 10); });
0

Just for note - if this A and B has nothing to do with sort, than go with parseInt as Zack posted.

But if it should be used in sort, you can go with something like this:

arr.sort(function(l,r){
  var vl = l[0].split(/(\d+)(\D*)/),
      vr = r[0].split(/(\d+)(\D*)/);

  vl[1] = parseInt(vl[1]);
  vr[1] = parseInt(vr[1]);

  if(vl[1] < vr[1]){
    return -1;
  }else if(vl[1] === vr[1]){
      if(vl[2] < vr[2]) return -1;
      else if(vl[2] === vr[2]) return 0;
      else return 1;
  }else{
      return 1;
  }
}); 

Comments

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.