Sort an array of objects based on another array of ids

后端 未结 10 2083
故里飘歌
故里飘歌 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:14

    Here's an alternative construction using Ramda that might be a bit more succinct, and the functions are pretty easy to repurpose for other things.

    const {indexBy, prop, map, flip} = R
    const a = [2,3,1,4]
    const b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
    
    const toIndexById = indexBy(prop('id'))
    const findIndexIn = flip(prop)
    
    const c = map(findIndexIn(toIndexById(b)), a)
    console.log(c)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>

    0 讨论(0)
  • 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('<pre>' + JSON.stringify(b, 0, 4) + '</pre>');

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

    0 讨论(0)
  • 2020-11-28 17:22

    Plain javascript, using some methods of the Array (ES2015 standard)

    var a = [2,3,1,4];
    var b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
    var c = [];
    
    a.forEach(el => c.push(b.find(e => e.id == el)));
    
    document.write(JSON.stringify(c, 0, 2));

    0 讨论(0)
  • Or may be simpler

    b.sort(function(obj1,obj2){
       return a.indexOf(obj1.id) > a.indexOf(obj2.id)
    });
    
    0 讨论(0)
提交回复
热议问题