0

I am trying to sort array as shown of objects which contains alphanumeric value

[
{ bayid="A1",  status=0}, 
{ bayid="A7",  status=0}, 
{ bayid="A6",  status=0}, 
{ bayid="A5",  status=0}
]

i am using the .sort method which is shown below

var sortedArray = modifiedStatusArray.sort(function(a, b) {
                return +b.bayid > +a.bayid;
            });

but not sure how to sort and get the output as shown below

[

{ bayid="A7",  status=0}, 
{ bayid="A6",  status=0}, 
{ bayid="A5",  status=0},
{ bayid="A1",  status=0}
]

please help

DhanaLaxshmi
  • 424
  • 1
  • 11
  • 24
  • That sort method won't work for any data, let alone alphanumeric data. A sort callback isn't supposed to return a boolean. – nnnnnn Mar 10 '16 at 00:13
  • Try using just `.sort(function(a,b){ return b.bayid.match(/\d+/) - a.bayid.match(/\d+/) })` –  Mar 10 '16 at 00:19

2 Answers2

4

I notice that you have a problem with your objects, the definition of you variable should be as follows:

var data = [
    { bayid: "A1",  status: 0}, 
    { bayid: "A7",  status: 0}, 
    { bayid: "A6",  status: 0},
    { bayid: "A5",  status: 0}
];

You can use the sort function:

var sorted = data.sort(function(a, b){
    if( a.bayid === b.bayid ){
      return 0;
    } else if ( a.bayid < b.bayid ) {
      return 1;
    } else {
      return -1;
    }
});
console.log( sorted );

The sort function takes a function as an argument, that function behaves as a comparison function (optional argument), that sort the values of the array based on the returned value of the function.

From the spec:

The array elements are sorted according to the return value of the compare function

If the returned value is:

  • less than 0, sort a to a lower index than b.
  • 0 (equal to zero), leave a and b unchanged with respect to each other.
  • greater than 0, sort b to a lower index than a.

More information from the spec.

There is a very similar question on the site as well it might be helpful, if you search on the site before creating a new question.

Community
  • 1
  • 1
Crisoforo Gaspar
  • 3,740
  • 2
  • 21
  • 27
1

Your sort function should return 1, -1 or 0

var sortedArray = modifiedStatusArray.sort(function(a, b) {
    return a.bayid < b.bayid ? 1 : a.bayid > b.bayid ? -1 : 0;
});
isvforall
  • 8,768
  • 6
  • 35
  • 50