-1

So, I have a table of statuses. On this table of statuses I have a foreign_key representing the workflow that the status belongs to. enter image description here

Now my question is, looping through the list of statuses will put them in order of Id, but say I insert a new status and want it to be in certain location in the list not just added to the bottom how would i do that?

Do I need to add an extra field that I could use to manipualte the order in which the statuses are printed out?

This question is different from the one that it may be a copy of because, I am simply asking how to order array of objects if there is no unique identifier for order other than ID or an Index. I'm not looking for alphabetical or reversed.

Say I have array of statuses coming from my database like so

[
  {id: 1, status: 'receive'},
  {id: 2, status: 'scan'},
  {id: 3, status: 'prepare'},
  {id: 4, status: 'review'},
  {id: 5, status: 'complete'},
]

And then I want to insert a new object however I want it to be 4th in the list but of course when I create the new status it will just use the next ID available... so the array would like this

[
  {id: 1, status: 'receive'},
  {id: 2, status: 'scan'},
  {id: 3, status: 'prepare'},
  {id: 4, status: 'review'},
  {id: 5, status: 'complete'},
  {id: 6, status: 'file'},// this being the new status created
]

So now when I return an array of all statuses how could I actually place the status 4th in list with the given properties available like so

[
  {id: 1, status: 'receive'},
  {id: 2, status: 'scan'},
  {id: 3, status: 'prepare'},
  {id: 6, status: 'file'},// this being the new order of statuses
  {id: 4, status: 'review'},
  {id: 5, status: 'complete'},
]
TJ Weems
  • 1,086
  • 3
  • 21
  • 37

2 Answers2

1

Use native splice function. By passing 0 as the second parameter you are specifying you do not want to delete before that position, meaning, just inserting.

var data = [];
data[0] = "One";
data[1] = "Two";
data[2] = "Three";
data[3] = "Four";
data.splice(2, 0, "Custom");
console.log(data.join());
Alfredo A.
  • 1,697
  • 3
  • 30
  • 43
  • view my updated post and see if the scenario still applies – TJ Weems Nov 08 '18 at 19:25
  • 1
    I'm not getting your question. Where do you want to do the processing logic? In Javascript or in the backend? If it's in Javascript, my answer is still the same. You might want to add another field, e.g. **seq_order** where you will have full control, and modify it and sort your data by that new field in your backend. – Alfredo A. Nov 08 '18 at 20:23
  • that's the advice I was looking for. If it is best practice to add a field such as `seq_order` to control the order in which an array of objects would be listed. it was apart of my original question. Thank you for the advice! – TJ Weems Nov 08 '18 at 20:34
0

look into Array.sort() for sorting and Array.splice for inserting at a given location.

Intervalia
  • 10,248
  • 2
  • 30
  • 60