Sort an array of objects based on another array of ids

后端 未结 10 2120
故里飘歌
故里飘歌 2020-11-28 16:27

I have 2 arrays

a = [2,3,1,4]
b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]

How do I get b sorted based on a? My desir

10条回答
  •  情歌与酒
    2020-11-28 17:19

    This solution uses Array#sort with a helper object c for the indices.

    {
        "1": 2,
        "2": 0,
        "3": 1,
        "4": 3
    }
    

    var a = [2, 3, 1, 4],
        b = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
        c = a.reduce(function (r, a, i) {
            r[a] = i;
            return r;
        }, {});
    
    b.sort(function (x, y) {
        return c[x.id] - c[y.id];
    });
    
    document.write('
    ' + JSON.stringify(b, 0, 4) + '
    ');

    For greater objects, I suggest to use Sorting with map.

提交回复
热议问题