Sort array of objects in specific order

前端 未结 5 833
清酒与你
清酒与你 2021-02-11 04:14

I have an array of objects returning from an API call which I need to sort into a specific format.

I\'m trying to organise the destination_country_id alphab

5条回答
  •  迷失自我
    2021-02-11 04:43

    you can use underscore sortBy method:

    a=[{obj:'first3'},{obj:'first2'},{obj:'first1'},{obj:'z'},{obj:'m'},{obj:'c'},{obj:'end3'},{obj:'end2'},{obj:'end1'}]
    a=_.sortBy(a,function (t,i){if (i<=2) return String.fromCharCode(0);if(i>=a.length-3) return String.fromCharCode(255);return t.obj })
    
    console.log(JSON.stringify(a))
    
    [{"obj":"first3"},{"obj":"first2"},{"obj":"first1"},{"obj":"c"},{"obj":"m"},{"obj":"z"},{"obj":"end3"},{"obj":"end2"},{"obj":"end1"}]
    

    http://jsfiddle.net/43Q8h/

提交回复
热议问题