在javascript中对对象数组进行排序

时间:2018-11-12 11:42:17

标签: javascript node.js

我有以下数组,我的目标是根据每个对象的address._id字段对数组进行排序,我尝试了lodash orderby函数,但未获得期望的结果。

[{
        rider_ids: '5b7116ea3dead9870b828a1a',
        is_dropoff: false,
        address: {
            type: 'home',
            city: 'Greater Noida',
            _id: '5b6d62524b4dc03c478ec129'
        }
    },
    {
        rider_ids: '5b7116ea3dead9870b828a1a',
        is_dropoff: true,
        address: {
            type: 'school',
            city: 'Noida',
            _id: '5b76d0631af1adaeabb44100'
        }
    },
    {
        rider_ids: '5b7116ea3dead9870b828a3w',
        is_dropoff: true,
        address: {
            type: 'school',
            city: 'Noida',
            _id: '5b76d0631af1adaeabb44188'
        }
    },
    {
        rider_ids: '5b7116ea3dead9870b828a8a',
        is_dropoff: true,
        address: {
            type: 'school',
            city: 'Noida',
            _id: '5b76d0631af1adaeabb44122'
        }
    }
]

1 个答案:

答案 0 :(得分:4)

非常简单的排序

 const foo = [{
            rider_ids: '5b7116ea3dead9870b828a1a',
            is_dropoff: false,
            address: {
                type: 'home',
                city: 'Greater Noida',
                state: 'Uttar Pradesh',
                full: 'Amrapali Leisure Valley, Greater Noida, Uttar Pradesh, India',
                lat: 28.5887034,
                lng: 77.4271665,
                latLng: '28.5887034,77.4271665',
                _id: '5b6d62524b4dc03c478ec129'
            }
        },
        {
            rider_ids: '5b7116ea3dead9870b828a1a',
            is_dropoff: true,
            address: {
                type: 'school',
                city: 'Noida',
                state: 'Uttar Pradesh',
                zipCode: '201301',
                full: 'B-38 C/2, Sector 57, Noida, Uttar Pradesh 201301, Noida, Uttar Pradesh 201301, India',
                lat: 28.6051165,
                lng: 77.3546077,
                latLng: '28.6051165,77.3546077',
                _id: '5b76d0631af1adaeabb44100'
            }
        }
    ]
    
console.log(foo.sort((a,b) => a.address._id.localeCompare(b.address._id)));