How to sort an array of structs in ColdFusion

后端 未结 10 1792
余生分开走
余生分开走 2020-12-17 10:00

I have an array of structs in ColdFusion. I\'d like to sort this array based on one of the attributes in the structs. How can I achieve this? I\'ve found the StructSort fun

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 10:24

    The accepted solution (from CFLib.org) is NOT safe. I experimented with this for something I needed to do at work and found that it returns incorrect results when sorting numeric with floats.

    For example if I have these structs: (pseudocode)

    
    a = ArrayNew(1);
    
    s = StructNew();
    s.name = 'orange';
    s.weight = 200;
    ArrayAppend(a, s);
    
    s = StructNew();
    s.name = 'strawberry';
    s.weight = 28;
    ArrayAppend(a, s);
    
    s = StructNew();
    s.name = 'banana';
    s.weight = 90.55;
    ArrayAppend(a, s);
    
    sorted_array = arrayOfStructsSort(a, 'weight', 'asc', 'numeric');
    
    

    Iterate over the sorted array and print the name & weight. It won't be in the right order, and this is a limitation of mixing an arbitrary key with the value being sorted.

提交回复
热议问题