How to sort an array of structs in ColdFusion

后端 未结 10 1770
余生分开走
余生分开走 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:23

    You can use the Underscore.cfc library to accomplish what you want:

    arrayOfStructs = [
        {myAttribute: 10},
        {myAttribute: 30},
        {myAttribute: 20}
    ];
    
    _ = new Underscore();
    
    sortedArray = _.sortBy(arrayOfStructs, function (struct) {
        return struct.myAttribute;
    });
    

    Underscore.cfc allows you to define a custom comparator and delegates to arraySort(). You can use it for sorting arrays, structs, queries, or string lists, but it always returns an array.

    (Disclaimer: I wrote Underscore.cfc)

提交回复
热议问题