简体   繁体   中英

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

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. And then compare the index of field on the order array.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM