How can I sort javascript array in the following order - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How can I sort javascript array in the following order

asifakhtarasifakhtar Posts: 3Member

down vote favorite

I have an array which I want to sort in the following order: gBookingsArray's StartDate without the value 'Call to Confirm' and gBookingsArray's Distance other than empty should come at the top of the array sorted by gBookingsArray's Distance then followed by rows where gBookingsArray's Location is "To Be Announced" and gBookingsArray's Distance is empty and then followed by rows where gBookingsArray's StartDate with value 'Call to Confirm' should come at the bottom of with array sorted by gBookingsArray's Distance.

After sorting the array gBookingsArray[2] shoud be first then gBookingsArray[0] then gBookingsArray[1] then gBookingsArray[4] and gBookingsArray[3]

My Array:
gBookingsArray[0] = new Object();
gBookingsArray[0].StartDate = 'Fri November 15, 2013';
gBookingsArray[0].Location = 'A';
gBookingsArray[0].Distance = 10;

gBookingsArray[1] = new Object();
gBookingsArray[1].StartDate = 'Fri November 15, 2113';
gBookingsArray[1].Location = 'To Be Announced';
gBookingsArray[1].Distance = '';

gBookingsArray[2] = new Object();
gBookingsArray[2].StartDate = 'Wed November 13, 2013';
gBookingsArray[2].Location = 'B';
gBookingsArray[2].Distance = 5;

gBookingsArray[3] = new Object();
gBookingsArray[3].StartDate = 'Call to Confirm';
gBookingsArray[3].Location = 'AAA';
gBookingsArray[3].Distance = 20;

gBookingsArray[4] = new Object();
gBookingsArray[4].StartDate = 'Call to Confirm';
gBookingsArray[4].Location = 'BBB';
gBookingsArray[4].Distance = 1;

function SortDistance(A, B)
{
try
{
if(A[3] == 'Call to Confirm' || B[3] == 'Call to Confirm')
return -1;

        if(A[7] == '' ||  B[7] == '')
            return -1;

        if (A[7] < B[7])                
            return -1;


        if (A[7] > B[7])            
            return 1;   

        return 0;
    }
    catch (err) 
    {
        alert(err.name + ': ' + err.message); alert('SortDistance(A, B)');
    }
}

function SortCallToConfirmDistance(A, B) 
{
    try 
    {               
        if(A[3] == 'Call to Confirm' &&  B[3] == 'Call to Confirm')     
        {
            if (A[7] < B[7])                
            return -1;


            if (A[7] > B[7])            
            return 1;           
        }               

        return 0;
    }
    catch (err) 
    {
        alert(err.name + ': ' + err.message); alert('SortCallToConfirmDistance(A, B)');
    }
}
Sign In or Register to comment.