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

后端 未结 5 833
有刺的猬
有刺的猬 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:45

    It's straightforward with lodash. The sortBy function will move the items to the sortindex position, so we just need to use find to get the corresponding object, and return its sortindex property for sortBy to use.

    var items = [{id:1, name:'bill'}, {id:2, name:'sam'}, {id:3, name: 'mary'}, {id:4, name:'jane'}];
    var order = [{id:1, sortindex:4}, {id:2, sortindex:2}, {id:3, sortindex: 1}, {id:4, sortindex:3}];
    
    var sorted = _.sortBy(items, function(item) {
      // sorts by the value returned here
      return _.find(order, function(ordItem) {
        // find the object where the id's match
        return item.id === ordItem.id;
      }).sortindex; // that object's sortindex property is returned
    });
    
    document.body.textContent = JSON.stringify(sorted);

提交回复
热议问题