Is there a way to organize a list of arrays within a loop based on a specific index within each array in JavaScript?

Greetings, I am currently facing an issue with sorting a specific object of arrays. The structure is as follows:

Allow me to provide a clearer example - I am receiving a string from an AJAX call formatted like this:

"name|price|blah|blah@name|price|blah|blah"

I am utilizing the split function to divide the string into two arrays using the delimiter @, and then further breaking them down by the | (pipe) separator. This results in the following:

As I iterate through each value in the arrays

 for(z = 0; z < actualarr.length; z++) {
   arr[1],
   arr[2]
   .....
 }


 ["name", "price", "blah" "blah"],
 ["name", "price", "blah" "blah"],
 ["name", "price", "blah" "blah"],
 ["name", "price", "blah" "blah"],
 ["name", "price", "blah" "blah"],
 ["name", "price", "blah" "blah"]

The challenge lies in the fact that these arrays are nested within a loop, treating each array as an individual item. My objective is to arrange these items based on the value of "price" found at a specific index. Your assistance in solving this matter would be greatly appreciated. Thank you!

Answer №1

Sorting the array must be done separately from its creation process. Once the entire array is generated, it can be sorted using Array#sort.

var string = "foo|42|blah1|blah2@bar|17|blah3|blah4",
    array = string.split('@').map(function (s) { return s.split('|'); });
    
array.sort(function (a, b) { return a[1] - b[1]; });

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

When attempting to send a GET request to the server, there is no response received, although the

I am having an issue with an ajax request I am sending to my server using jQuery's get function. The request is being sent successfully, as Firebug shows a 200 status code, but the server does not provide any response. Even when I enter the address di ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

Shake up your background with a random twist

Seeking assistance with customizing the Aerial template from HTML5UP. I am interested in selecting a scrolling background randomly from a pool of images. Can someone guide me on how to achieve this? Presently, the background is defined within a code block ...

Unlocking the treasures of JSON data in JavaScriptDiscovering the secrets of extracting JSON

let info = { "@type": "Movie", "url": "/title/tt0443272/", "name": "Lincoln", "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA ...

What causes an asynchronous function to exhibit different behavior when utilized in conjunction with addEventListener versus when manually invoked?

I was delving into the concepts of async and await keywords and decided to create a basic demonstration using an HTML file and a corresponding JS file. In my example, I defined two promises - promise1 and promise2. The handlePromises function uses async/ ...

Next JS Event Listener Failing to Detect Scroll Events

Currently, I am attempting to change the state and display a shadow in the navigation bar when the user scrolls, but for some reason it is not detecting the event. I am working with nextJS 13 and tailwind css. const [shadow, setShadow] = useState(false) ...

Adjust the shopping cart contents based on updated spinner values

Currently, I am working on an application that features a shopping cart with a DataTable. Within the cart, there is a spinner to indicate the quantity of each product. I want the shopping cart to refresh whenever the value of the spinner changes. Below is ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

An unexplained line break is being added to content loaded via ajax requests

When using either .ajax or .load to load content from an .html page and insert it into an element, I am experiencing a strange issue where a mysterious new line is appended after the content. It is not a break element, but more like a \n or \r ch ...

Expect a reply within the loop

One of my endpoints takes some time to generate data, and I have another endpoint to retrieve that generated data. I make the initial call using await, extract the ID from the response, and then keep calling the second endpoint until the status is not "Suc ...

Dynamic script appending encounters unforeseen challenges

After attempting to add a script either on click or after a time delay, I am encountering an issue where the script is not being appended. Strangely, if I remove the setTimeout function, the script gets added successfully. The same problem persists with ...

Is it possible to utilize the spread operator for combining arrays?

Consider two different arrays represented by variables a and b. The variable c represents the output as a single array, indicating that this method combines two or more arrays into one. let a=[a ,b]; let b=[c ,d]; c=[a,...b] The resulting array will be: ...

Solving the issue of overflowing in the animation on scroll library

I've recently started using a fantastic library called animation on scroll (aos) for my web development projects. This library offers stunning and visually appealing animations. However, I encountered an issue where it causes overflow problems in my H ...

Determine the absolute path with respect to a different reference path, rather than the current working directory

One of the challenges I'm facing with my Node.js module is how to easily allow developers to edit the location of the dependencies relative to the module file itself. The issue arises because the current working directory, accessed through `process.cw ...

"Handsontable organizes information pulled directly from the backend database using JSON/AJAX

In order to implement the Handsontable column sorting and direction indicators, I would like to create a mechanism that sends sort requests to my database and displays the corresponding results. Although the Handsontable sort plugin is effective in allowi ...

Submitting a form with multiple actions using Ajax

Is it possible to submit data from multiple forms on the same page to different API tables using AJAX for each form? I have one form that needs to write to one table and another form that needs to write to a different table. How can I achieve this with o ...

Tips for implementing both an onChange and onSubmit event for a MUI TextField

I'm currently working with React and MUI and have created a form like the following: const handleUserInput = (event) => { set_user_input(event) } const handleSubmitForm = () => { if (user_input == 'help'){ ...

Error in ng-repeat loop: detecting duplicates when none are present

$scope.subjects = [ "Computer Security", "Graphics and Multimedia", "Networks", "Computer Science and Engineering", "Game Design", "Programming", "Information Technology", "Software Engineering", "Technology Manageme ...

Having trouble getting the jQuery autocomplete feature to function properly?

On my page, there is a button labeled "Add a Skill." Clicking on this button should trigger the display of an input box where you can enter your skill, another input box for your skill level, and a horizontal slider to select the skill level. In my databa ...