john316
john316

Reputation: 83

Array sort and value change at the same time

I have an array below and the first number in each array means order. What I want to do is, whenever I change the order, it resorts the array and re-index it into 2, 3, 4, 5.

const payments = [
    [2, paymentName1, '5%'],
    [3, paymentName2, '5%'],
    [4, paymentName3, '5%'],
    [5, paymentName4, '5%']
  ];

For example, if I change the first array order from 2 to 6, array becomes the one below.

const payments = [
    [2, paymentName2, '5%'],
    [3, paymentName3, '5%'],
    [4, paymentName4, '5%'],
    [5, paymentName1, '5%'],
  ];

what I currently did was to sort it and take for loop to re-order it. and I want to do it in one loop if possible. Please help me with writing this algorithm.

Thanks 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 function. Would there be a better way to do? thanks!

Upvotes: 0

Views: 989

Answers (1)

trincot
trincot

Reputation: 350272

After you sort, just loop over the array and assign the new order values incrementally. There is no "better" here.

const payments = [
    [2, "paymentName1", '5%'],
    [3, "paymentName2", '5%'],
    [4, "paymentName3", '5%'],
    [5, "paymentName4", '5%']
];

function setOrder(index, newOrder) {
    payments[index][0] = newOrder;
    payments.sort(([a], [b]) => a - b);
    for (let i = 0; i < payments.length; i++) payments[i][0] = i + 2;
}

setOrder(0, 6);
console.log(payments);

The time complexity is determined by the call to sort: O(nlogn).

Alternatively, you could use binary search to find the target index where the mutated element should go, and then rotate the array elements accordingly. Then the time complexity will be O(n). Although this has a better time complexity, the overhead of JavaScript code will make that for arrays of moderate sizes you'll get faster results with sort.

Upvotes: 2

Related Questions