Skip to main content
jibinanto40792294
Inspiring
November 23, 2021
Answered

Multiple sort

  • November 23, 2021
  • 1 reply
  • 516 views

Hi,

Would like to know is it possible to have multiple sort in array of structures
In other words,is there any equivalent function for multi_sort like in php?

For example,in the below product color information,want primary sort using product style column and secondary sort using its color. ie,if same product has different color,sort again using color as below.

AA6040~~red
KP155~~Lime
KP155~~Orange

Tried using arraySort as below,but seems it can be used to sort using single key.


<cfscript>
local.ary_styleInfo = arrayNew(1);
authors = structnew();
authors
= {
style = 'KP155'
,color = 'orange'

};

//writeDump(authors);
arrayAppend(local.ary_styleInfo ,authors);
authors = structnew();
authors
= {
style = 'KP155'
,color = 'Lime'

};

//writeDump(authors);
arrayAppend(local.ary_styleInfo ,authors);
//2
authors = structnew();
authors
= {
style = 'AA6040'
,color = 'red'

};
//writeDump(authors);
arrayAppend(local.ary_styleInfo ,authors);

writeDump( local.ary_styleInfo );
//sort
arraySort(local.ary_styleInfo, function (e1, e2){
return compare(e1.style, e2.style);
}
);

writeDump('FINAL');

writeDump( local.ary_styleInfo )
</cfscript>

 

    This topic has been closed for replies.
    Correct answer BKBK

    @BKBK, thanks for the shout out.

     

    I didn't want to introduce the elvis operator here because it looks strange to those not familiar with it, but it is more succinct and definitely what I would use. 🙂


    On second thoughts, assuming Lime and lime represent the same colour, the correct versions of the solutions are:

     

    if (compareNoCase(e1.style, e2.style) == 0)
    return compareNoCase(e1.color, e2.color);
    return compareNoCase(e1.style, e2.style);

     

    or

     

    return compareNoCase(e1.style, e2.style) ?  compareNoCase(e1.style, e2.style) : compareNoCase(e1.color, e2.color);

     

     

     

     

    1 reply

    EddieLotter
    Inspiring
    November 23, 2021

    You were very close.

    Add the following two lines before the existing return statement (also included below) in your lambda function:

    if (compare(e1.style, e2.style) == 0)
      return compare(e1.color, e2.color);
    return compare(e1.style, e2.style);
    BKBK
    Community Expert
    Community Expert
    November 24, 2021

    Or, equivalently, as 1 line ( with credit to @EddieLotter ) 

     

     return compare(e1.style, e2.style) ?  compare(e1.style, e2.style) : compare(e1.color, e2.color);

     

     

    EddieLotter
    Inspiring
    November 24, 2021

    @BKBK, thanks for the shout out.

     

    I didn't want to introduce the elvis operator here because it looks strange to those not familiar with it, but it is more succinct and definitely what I would use. 🙂