Sort an array of objects based on another array of ids

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

    I am going to iterate on arcseldon's solution.

    The right approach here is to flip the problem, instead of "sorting a based on the order given by b", I'd rather "enrich b with data coming from a"

    This lets you maintain the time complexity of this function down to O(n), instead of bringing it up to O(n2).

    const pickById = R.pipe(
      R.indexBy(R.prop('id')),
      R.flip(R.prop),
    );
    
    const enrich = R.useWith(R.map, [pickById, R.identity]);
    
    
    // =====
    
    const data = [2, 3, 1, 4];
    const source = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
    
    console.log(
      enrich(source, data),
    );

提交回复
热议问题