1

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
2
  • 1
    Do both arrays always have the same length? Or could it happen, that the Object-Array (the one you want to sort) has more entries than the array of objectIds? Commented May 18, 2022 at 12:44
  • Does stackoverflow.com/a/1129270/1901635 help? Commented May 18, 2022 at 12:46

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Its not working for me. Should i a.field conver objectid
@ŞahinErsever ObjectId class is not defined here, so I changed it to string here for simplicity. What is ObjectId class definition?
data.field: new ObjectId("627f816d8443318c6aaa1220" from mongoose
@ŞahinErsever you should be able to use data.sort((a,b) => order.indexOf(a._id.toHexString()) - order.indexOf(b._id.toHexString()));
.toHexString() it worked thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.