Simultaneously sort and modify values within an array

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!

Answer №1

Once you have the array sorted, simply iterate over it and assign the updated order values one by one. There is no clear advantage to any other method in this scenario.

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 ultimately depends on the sort function: O(nlogn).

Alternatively, you could opt for binary search to pinpoint the exact position where the modified element should be inserted, then adjust the array elements accordingly. This would result in a time complexity of O(n). However, in practice, due to JavaScript's execution overhead, using sort may still yield quicker results when dealing with arrays of modest sizes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for opening a clicked link in a new tab:

I have a link on my page that I would like to open in a new tab when clicked, but it doesn't seem to be working. Can anyone offer some suggestions or help? So far, I've tried the following code: <a target="_BLANK" ng-href="{{news.url ...

When using SuperTest, the Authorization header value may unexpectedly return undefined

Currently, I am working on writing tests using Mocha, Supertest, and Chai. In order for my API's to function properly, they require an Authorization header which can be obtained from req.headers["authorization"]. Below you will find the current setup ...

Encountering issues with proper function of history.listen within React Router

I am struggling to get my function to work every time React detects a change in the URL. The history.listen method is not triggering (the console.log statement is not showing up). I have read that this issue may be related to using BrowserRouter, but when ...

Having trouble creating an axios instance in Vue

I recently came across a helpful tip in an article about using axios for AJAX requests in Vue. The author mentioned that by setting Vue.prototype.$http = axios, we can then use this.$http within the Vue instance, which worked perfectly for me. However, wh ...

New issue with installing npm cra

Recently updated to npm version 6.14.4 and encountered an issue while trying to create a new app with cra-template. How can I resolve this problem? npx create-react-app sphinx.ui.react Error Log 50 timing stage:runTopLevelLifecycles Completed in 5234ms ...

How can I detect Mongoose events through syntax?

Is there a way to detect the open event in Mongoose based on their documentation located here? According to the documentation, once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is m ...

What is the best way to retrieve all the values of a specific field from a store?

Is there a way to retrieve all the values of a specific field from a store without manually selecting each cell? In my grid, I am looking to extract all the values from a particular column directly from the store. Is this achievable without any manual sel ...

How to pass an item as a parameter to a computed property in Vue.js, and have it return a sorted child array within a

After spending some time searching on Google, I am still struggling to find a solution for this issue. I have a list of "Intents" that contain nested lists of "Entities" created using v-for loops. The Intents are already computed, but now I need to dynam ...

Tips for integrating jwt token into axios request

I am facing an issue with my backend endpoint. I can successfully retrieve a list of customers using jwt token on Postman, but when I try to fetch the list from a React app using axios get request, it fails. After reading through this question, I implemen ...

Changing the color of a Highcharts series bar according to its value

Playing around with Highcharts in this plunker has led me to wonder if it's possible to dynamically set the color of a bar based on its value. In my current setup, I have 5 bars that change values between 0 and 100 at intervals. I'd like the colo ...

Storing form data in a JSON file using JavaScript

For a while now, I've been pondering over this issue. My plan involves creating a desktop application with Electron. As a result, I am working on an app using Node.js and Express.js. The project includes a simple app.js file that executes my website&a ...

Is it necessary to compile Jade templates only once?

I'm new to exploring jade in conjunction with express.js and I'm on a quest to fully understand jade. Here's my query: Express mentions caching jade in production - but how exactly does this process unfold? Given that the output is continge ...

Issue encountered when updating npm to version 5.4.2: Unable to locate modules in ./node_modules/react-router-dom

When attempting to update my npm version from 3.10.10 to 5.4.2 and migrate react from 15.3.0 to 16.0, I deleted the node_modules folder and re-ran npm install. However, upon trying to run my application again, I encountered the following error: ERROR in ./ ...

What steps do I need to take in order to include REMOVE and EDIT buttons in my table?

In the index.html file, there is a teacher table that is only displayed after clicking on the button Teachers: <div class="container"> <table class="teacherTable" border="1" width="100%" cellpadding=&qu ...

NodeJS Socket not transmitting file after connection with client

Having scoured the depths of various resources, including SO and Google, I have hit a roadblock. I am struggling to understand why the socket is failing to capture the uploaded file via the form; it simply stops after connecting. When I check the console, ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

Iterate through the array in order to showcase or output it in PHP syntax sourced from an API

[0] => Array ( [id] => 6 [name] => Digitally Imported Psy Goatrance [country] => GB [image] => Array ( [url] => https://img.dirble.com/station/6/original.png ...

What is the process of converting PUG to JSX?

I am currently attempting to integrate Pug code within a JS react application. While researching, I came across this plugin here, which can assist in converting the code. However, it seems to have an issue with handling the "." statements present in the c ...

Effective ways to engage with a window that is supervised by a different controller?

Although the question may appear vague initially, I struggled to find a better way to convey my idea. Let me elaborate on it in detail. In my SPA application, I have MasterController connected to the <html> tag. This MasterController consists of all ...

Obtain the ID of a YouTube video from an iFrame link using jQuery

Check out this YouTube video: iframe width="560" height="315" src="//www.youtube.com/embed/XbGs_qK2PQA" frameborder="0" allowfullscreen></iframe>` (Hell Yeah! Eminem :P) I only want to extract "XbGs_qK2PQA" from the link provided. Using $(&apo ...