Sort array of objects in specific order

前端 未结 5 1854
青春惊慌失措
青春惊慌失措 2021-02-11 03:51

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:41

    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/

提交回复
热议问题