[英]Sort array object based on another array in javascript
How can i sort and rearrange an array that looks like this我如何对看起来像这样的数组进行排序和重新排列
fields = [
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: new ObjectId("627f816d8443318c6aaa1220"
},
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: new ObjectId("6283cb3ca573a56e11587c46"),
}
]
to match the arrangement of this array:匹配这个数组的排列:
order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ]
Here is the output I'm looking for:这是我正在寻找的输出:
[
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: new ObjectId("6283cb3ca573a56e11587c46"),
},
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: new ObjectId("627f816d8443318c6aaa1220"),
}
]
findIndex and sort but I am very confused findIndex 和排序,但我很困惑
fields.sort((a: any, b: any) => order.indexOf(a.field) - order.indexOf(b.field)) // It does not work
You need to use sort
method on the array.您需要对数组使用
sort
方法。 And then compare the index of field
on the order array.然后比较订单数组上的
field
索引。
const data = [ { uid: '2aa60f96-135b-e179-2b46-516c87a877cc', field: "6283cb3ca573a56e11587c46", value: 'test val 6' }, { uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d', field: "627f816d8443318c6aaa1220", value: '' } ] const order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ]; data.sort((a,b) => order.indexOf(a.field) - order.indexOf(b.field)); console.log(data);
Notice: ObjectId
class is not defined here, so I changed it to string here for simplicity.注意:这里没有定义
ObjectId
类,所以为了简单起见,我在这里将其更改为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.