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

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

    If you store your order as a map, it's rather straight forward with vanilla Javascript.

    var items = [{id:1, name:'bill'}, {id:2, name:'sam'}, {id:3, name: 'mary'}, {id:4, name:'jane'}];
    var order = {1:4, 2:2, 3:1, 4:3};
    items.sort(function (a, b) {
        return (order[a.id] > order[b.id]) - (order[a.id] < order[b.id]);
    });
    

    Or if you insist on your original data, assuming it's already sorted as you show it to be:

    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}];
    
    items.sort(function (a, b) {
        var ai = order[a.id - 1].sortindex;
        var bi = order[b.id - 1].sortindex;
        return (ai > bi) - (ai < bi);
    });
    

    If you can't assume the data is sorted, see this question, for example on how to create a map from your data.

提交回复
热议问题