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

Error in Cordova application for Windows Phone 8.1 due to disrupted AJAX responses

Currently, we are utilizing Cordova 3.4.0 for the development of our application. We have successfully tested and run the app on Android and iOS devices, as well as on desktop browsers without any issues. However, we have encountered a peculiar problem spe ...

Is it better to use Rollup for exporting individual components instead of lumping them all into one index.js

Currently, I am working on developing a custom component library using React and Rollup for bundling. The current setup bundles all components into two large files: dist ├ cjs │ └ index.js (1.7mb) └ esm └ index.js (1.7mb) I would like to ...

Unable to retrieve the saved user from the Express.js session

Below is the code in question: app.post('/api/command', function (req, res, next) { var clientCommand = req.body.command; console.log("ClientCommand: ", clientCommand); if (!req.session.step || req.session.step === EMAIL) { ...

Having trouble parsing the BODY of a NodeJs JSON post request?

I've been working on creating a basic API using nodeJS, but I've run into a problem while trying to post data. Below is my app.js file: const express = require('express'); const feedRoutes = require('./routes/feed'); const ...

Is there a way to transfer multiple functions using a single context?

Having created individual contexts for my functions, I now seek to optimize them by consolidating all functions into a single context provider. The three functions that handle cart options are: handleAddProduct handleRemoveProduct handleC ...

The npm module parsing has encountered an error... It appears that a suitable loader is required to process this file format

Recently, I made changes to an open-source code that was working perfectly until yesterday. I can't seem to figure out what went wrong as I didn't make any significant changes. Despite searching on Stack Overflow for a similar issue, my lack of k ...

Utilizing a Static Image Path Prop in React JS: A Step-by-Step Guide

My Main Component import React from "react"; import TopModal from "./components/topModal"; // Passing productImage to the Child Component import productImage from "../../../../../../assets/images/juices.jpg"; import { makeS ...

Iterating through associative arrays in Laravel to retrieve individual results even when there are additional results to be fetched

Having an issue with a query returning an associative array. Specifically, when attempting to run an if statement to check if one date equals another, the condition only seems to apply to the first value 2017-09-21. The query in question: $startDates = A ...

Loading files using $scriptjs or any other asynchronous loader allows for seamless integration of external resources

Imagine I have developed an AngularJS application that lazy loads controller files (using $scriptjs) and all dependencies when the user navigates to a specific route. This application consists of 3 routes: A, B, and C. My question is: if the user navigate ...

Is there a way to execute a function after EACH user interaction?

I am in the process of developing a React Native kiosk application for an Android tablet that will be mounted on a wall. The main requirement is to include a "screen saver" feature, where if the user does not interact with the screen for 30 seconds, it wil ...

It is my goal to populate the array with numbers while avoiding any duplicate entries

I am currently facing an issue with my code as it is returning a length of 0 instead of the expected result of 5 after excluding duplicates from the array. I have a feeling that there might be something missing in my code, but I just can't seem to fig ...

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

Managing key presses with functions in VueJs

Within my component, I am utilizing VueStrap's modal in the following manner: <template> <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed=" ...

Managing Chrome application authentication pop-up with Selenium Webdriver and C#

I have come across numerous discussions on this matter but none of the solutions seem to be effective. I am looking for a way to input the username and password into the chrome authentication alert using Selenium Webdriver with C# code. ...

Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes. The approach involves ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

When trying to make a POST request, the browser displayed an error message stating "net::ERR_CONNECTION

Currently, my project involves coding with React.js on the client side and Express.js on the server side. I have encountered an issue when attempting to use the POST method to transmit data from the client to the server for storage in a JSON file. The erro ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

Is there a problem with `window.google` being undefined in a React

Every time I call window and use console log, a google prop appears as shown below: https://i.sstatic.net/dSMs8.png But then when I attempt to call window.google, it returns undefined. Am I overlooking something here? ...

Navigating array usage in Selenium IDE

I am trying to extract emails from a webpage using Selenium for future testing. I need to compare these emails with ones displayed in a selection later on. I attempted to read the emails within a while-loop but struggled with handling arrays in IDE. Unfor ...