0

I'm trying to update a private variable inside of a class. The variable is an array with objects in it. The goal is to have the array.index values swap places for drag and drop functionality. However, I keep getting unexpected results when trying to swap them.

let sortOrder = [{
    index: 0,
    indexOrigin: 0
  },
  {
    index: 1,
    indexOrigin: 1
  },
  {
    index: 2,
    indexOrigin: 2
  },
  {
    index: 3,
    indexOrigin: 3
  }
];

let sort = class {
  #sortOrder;
  constructor() {
    this.#sortOrder = [{
        index: 0,
        indexOrigin: 0
      },
      {
        index: 1,
        indexOrigin: 1
      },
      {
        index: 2,
        indexOrigin: 2
      },
      {
        index: 3,
        indexOrigin: 3
      }
    ];
  }

  updateSortOrder(i1, i2) {
    let sortOrderClone = structuredClone(sortOrder);
    this.#sortOrder[i1].index = sortOrderClone[i2].index;
    this.#sortOrder[i2].index = sortOrderClone[i1].index;
    console.log(this.#sortOrder);
  }

}

let test = new sort();

test.updateSortOrder(2, 3);
test.updateSortOrder(1, 2);
test.updateSortOrder(0, 1);

What I expect is by the 3rd console.log it should display:

[{
  index: 3,
  indexOrigin: 0
}, {
  index: 0,
  indexOrigin: 1
}, {
  index: 1,
  indexOrigin: 2
}, {
  index: 2,
  indexOrigin: 3
}]

but what actually displays is:

[
  {
    "index": 1,
    "indexOrigin": 0
  },
  {
    "index": 0,
    "indexOrigin": 1
  },
  {
    "index": 1,
    "indexOrigin": 2
  },
  {
    "index": 2,
    "indexOrigin": 3
  }
]

It's consistently correct on the 1st time the function is run, but after that 1st run, it returns unexpected results. Would appreciate any feedback as to why it behaves this way.

TK421
  • 801
  • 5
  • 16
  • 24
  • Could it be that by the time you assign the second swap, the first swaps value is already changed? You might need to temporarily store what is at the current index: `const second = sortOrderClone[i1].index; this.#sortOrder[i1].index = sortOrderClone[i2].index; this.#sortOrder[i2].index = second;`? Or in simpeler terms: `const a = array[1]; array[1] = array[0]; array[0] = a; ` – somethinghere Aug 21 '23 at 13:47
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Aug 21 '23 at 14:42

1 Answers1

0

You need to modify your sortOrder Object after the sort operation.Otherwise your sortOrderClone Object will be outdated with each change.

updateSortOrder(i1, i2) {
  let sortOrderClone = structuredClone(sortOrder);
  this.#sortOrder[i1].index = sortOrderClone[i2].index;
  this.#sortOrder[i2].index = sortOrderClone[i1].index;
  sortOrder = this.#sortOrder;
  console.log(this.#sortOrder);
}
tobireinbo
  • 56
  • 1