Şahin Ersever
Şahin Ersever

Reputation: 356

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

Upvotes: 1

Views: 120

Answers (1)

Amir MB
Amir MB

Reputation: 3420

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.

Upvotes: 2

Related Questions