0

I have an array of objects and each object can have a order prop. Now I want to reorder this array by updating one objects order number. Its siblings should then get updated so that its order makes sense again.

Base:

  • 01: no order
  • 02: order 4
  • 03: order 2
  • 04: no order

Steps if 04 get fixed position 2:

Step 1
  • 01: order 0
  • 02: order 4
  • 03: order 2
  • 04: no order
Step 2
  • 01: order 0
  • 03: order 2
  • 04: no order
  • 02: order 4
Step 3
  • 01: order 0
  • 03: order 1
  • 04: no order
  • 02: order 4
Step 4
  • 01: order 0
  • 03: order 1
  • 04: order 2
  • 02: order 4
Step 5
  • 01: order 0
  • 03: order 1
  • 04: order 2
  • 02: order 3

With the case when 04 gets a fixed position of 1, 02 would be on the same index so since 04 is fixed 02 get 04 old index or current + 1.

muuvmuuv
  • 901
  • 2
  • 13
  • 39
  • How do you decide if `03` gets pushed down to order 1 or up to order 3? How do you decide to order the elements that have `no order`? – Jannes Carpentier Aug 05 '20 at 08:10
  • Sounds like normal sorting by key, or did I miss something? https://stackoverflow.com/q/8837454/5520354 – C14L Aug 05 '20 at 08:12
  • @JannesCarpentier based on their index. 02 gets shifted to the end so 03 gets index 1 and 04 index 2. – muuvmuuv Aug 05 '20 at 08:13
  • No @C14L, because I want to update the order property of all siblings AND keep the index of 04 at 2. – muuvmuuv Aug 05 '20 at 08:15

1 Answers1

0

I think you want something like this:

  1. You update the order of an element
  2. You sort them
  3. You update the order values

const data = [{
  i: 1,
  order: "no order"
}, {
  i: 2,
  order: 4
}, {
  i: 3,
  order: 2
}, {
  i: 4,
  order: "no order"
}];

function printData() {
  data.forEach(x => console.log(x.i, x.order));
}

function changeOrderAndSort(index, order) {
  data[index].order = order;
  printData();

  data.sort((a, b) => a.order - b.order);
  console.log("--")
  printData();

  for (let i = 0; i < data.length; i++) {
    data[i].order = i;
  }
  console.log("--")
  printData();
}

changeOrderAndSort(3, 2);
Jannes Carpentier
  • 1,838
  • 1
  • 5
  • 12
  • That works pretty good, thank you. Just noticed that giving `3` an index of `0` does not work. Will try to build on that. – muuvmuuv Aug 05 '20 at 08:44
  • That is because I just change its order value, not placing it at a certain index. Also the object with `order: "no order"` will not be moved by the sort function. – Jannes Carpentier Aug 05 '20 at 08:54