Sort an array of objects based on another array of ids

后端 未结 10 2122
故里飘歌
故里飘歌 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)

提交回复
热议问题