I am working with an array where the first number in each sub-array indicates the order. Whenever I change the order, I need to rearrange the array and re-index it starting from 2, 3, 4, 5.
const payments = [
[2, paymentName1, '5%'],
[3, paymentName2, '5%'],
[4, paymentName3, '5%'],
[5, paymentName4, '5%']
];
For instance, if I change the order of the first sub-array from 2 to 6, the array should look like this:
const payments = [
[2, paymentName2, '5%'],
[3, paymentName3, '5%'],
[4, paymentName4, '5%'],
[5, paymentName1, '5%'],
];
Currently, I sort the array and then use a for loop to reorder it. I am looking for a more efficient way to accomplish this task using just one loop. Any help on writing this algorithm would be greatly appreciated.
Thank you in advance!
Edit:
payments.sort((a, b) => a[0] - b[0]);
for (const index in payments) {
payments[index][0] = parseInt(index) + 2;
}
This is my current approach. Is there a better way to achieve this task?
Thank you for your assistance!