how to sort an array of objects using a related property from objects in second array

后端 未结 5 825
有刺的猬
有刺的猬 2021-01-26 09:06

There are many questions regarding sorting with JavaScript but I didn\'t find anything that addresses this case so I don\'t believe this is a duplicate.

I\'m getting dat

5条回答
  •  时光说笑
    2021-01-26 09:50

    Here's my solution. If you know that both arrays will match in length and location of id's, then this is a concise solution:

    _.chain(items)
     .merge(order)
     .sortBy('sortindex')
     .map(_.partialRight(_.omit, 'sortindex'))
     .value()
    

    Otherwise, if they aren't guaranteed to be sorted, then the items can be resolved with a map/find/merge.

    _.chain(items)
     .map(function(item) { 
        return _.merge(item, _.find(order, {'id': item.id})); 
     })
     .sortBy('sortindex')
     .map(_.partialRight(_.omit, 'sortindex'))
     .value()
    

提交回复
热议问题