I have following array of objects.
[
{ id: 1, title: 't1', order: 0 },
{ id: 2, title: 't1', order: 1 },
{ id: 3, title: 't1', order: 2 },
]
I want to reorder items several times.
In the first try.
// move id: 1, fromOrder: 0, toOrder: 2
[
{ id: 1, title: 't1', order: 2 },
{ id: 2, title: 't2', order: 0 },
{ id: 3, title: 't3', order: 1 },
]
In the second try.
// move id: 3, fromOrder: 1, toOrder: 0
[
{ id: 1, title: 't1', order: 2 },
{ id: 2, title: 't2', order: 1 },
{ id: 3, title: 't3', order: 0 },
]
As you can see the point is that I am not going to move the item, I just want to update the order attribute.
I did something like below but it does not work as expected.
const reorder = (array, id, oldIndex, newIndex) => {
const ordered = array
.map(item => item.order === newIndex ? { ...item, order: oldIndex } : item)
.map(item => item.id === id ? { ...item, order: newIndex } : item);
return ordered;
};
Post Answer Third Party Clarification Edit
The user wanted to shift all item's orders around (including wrapping around), rather than just swapping two values, preserving the relative orders.
orderbased on recent update array. There is no specific rule.arr = reorder(arr, 1, 2, 2); arr = reorder(arr, 2, 0, 1); arr = reorder(arr, 3, 1, 0);