根据另一个id数组对对象数组进行排序

32

我有两个数组

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

如何根据 ab 进行排序?我想要的输出结果是

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

我更倾向于使用Ramda或普通JS。


1
真正的 b 对象除了 id 之外还包含其他内容吗? - georg
可能是Javascript - sort array based on another array的重复问题。 - Heretic Monkey
12个回答

0
这里有一个使用Ramda的替代建构方式,可能更加简洁,而且这些函数很容易重用到其他事情上。

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

你可以简单地使用Reduce

    var a = [2, 3, 1, 4];
    var c = a.reduce((res,item)=>([...res,{'id':item}]),[])
    console.log(c)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接