Arranging an array of JSON objects without keys in a specific order

Here is an array containing multiple objects without any keys:

const result = [
  ["Joe", "1", "2.22%", "$3,000.00"], 
  ["Tom", "1", "2.22%", "$4,650.00"], 
  ["Ryan", "4", "4.44%", "$18,925.00"], 
  ["Jordan", "2", "4.44%", "$3,300.00"], 
  ["Fred", "0", "0.00%", "$0.00"], 
  ["Steve", "0", "0.00%", "$0.00"]
]

I'm having difficulty trying to sort the array by the fourth object. Is there a simple way to achieve this sorting without modifying the original array?

The desired outcome is to return the sorted results in descending order based on the fourth object.

return {result: result[2][0] + ": " + result[2][3] + '\n' + result[1][0] + ': ' + result[1][3] + '\n' + result[3][0] + ': ' + result[3][3] + '\n' + result[0][0] + ': ' + result[0][3] + '\n' + result[4][0] + ': ' + result[4][3] + '\n' + result[5][0] + ': ' + result[5][3] };

The returned results will appear as follows:

Ryan: $18,925.00

Tom: $4,650.00

Jordan: $3,300.00

Joe: $3,000.00

Fred:$0.00

Steve: $0.00

Answer №1

To obtain a standardized numeric value and calculate the difference for sorting, you can eliminate any undesired characters.

const standardize = str => str.replace(/[^\d.]/g, '');

var data = [["Joe", "1", "2.22%", "$3,000.00"], ["Tom", "1", "2.22%", "$4,650.00"], ["Ryan", "4", "4.44%", "$18,925.00"], ["Jordan", "2", "4.44%", "$3,300.00"], ["Fred", "0", "0.00%", "$0.00"], ["Test", "0", "0.00%", "$0.00"]],
    output = data
        .sort((a, b) => standardize(b[3]) - standardize(a[3]))
        .map(({ [0]: name, [3]: amount }) => [name, amount]);

console.log(output);

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

Activate the search feature in select2 to allow multiple selections

I'm looking for a way to incorporate a search box into my multi-select fields using select2. Oddly enough, while the search boxes show up as expected in single-select fields, applying the same select2() function to a multi-select field doesn't s ...

Enhancing MongoDB query efficiency using Promise technology

At the moment, I am deeply involved in a personal project that is presenting a challenge with two different approaches to querying MongoDB. CustomerSchema.methods.GetOrders = function(){ return Promise.all( this.orders.map(orderId => Order. ...

Limiting the draggable element within a compact container using jquery UI

I've been attempting to drag an <img> within a fixed-width and fixed-height container. Despite researching on Stack Overflow and finding this solution, it doesn't seem to work for my specific case. If you check out this fiddle I created, y ...

How can I use JavaScript api calls to retrieve an image url and insert it into an image tag in an

I have a JSON object that I need to use to retrieve images from a remote URL and display them in the img tag using API calls. The API link can be found at <div class="emoji"> <ul id="emojiz"></ul> <span style= ...

Using JavaScript to trigger actions via links or buttons inside a table will only function properly in the first row

After multiple consecutive Ajax requests to refill an HTML table, there seems to be a strange issue. The links in the first row of the table are functioning properly and call JavaScript functions, but for any subsequent rows, the links or buttons stop work ...

What is the best way to insert a new value into an already existing JSON array?

My JSON structure looks like this: { "intents": [ { "tag": "greeting", "patterns": [ "Hi there", "How are you", ...

What could be causing the initial element of a class returned by Jarray.ToObject to consistently be null, despite the presence of assigned data in the JSON?

Trying to Deserialize data from a public API, like this: [ { "title": "Bitcoin", "symbol": "₿", "rank": 1, "age": 4913, "color": "#fa9e32", "pn ...

Special character decoding in JSON format

My string is test éàå. When I use json_encode, the special character changes to test u00e9u00e0u00e5. After using json_decode, I am unable to retrieve the original characters and it remains as test u00e9u00e0u00e5 Does anyone know how to recover th ...

Struggling with loading external scripts within background.js in Chrome extensions?

I am facing an issue with my chrome extension. I am unable to call an external script, specifically the ethereum script (web3.min.js), from within my background.js file. The error message I receive is: Uncaught EvalError: Refused to evaluate a string ...

Utilize a variable within a regular expression

Can the variable label be used inside a regex like this? const label = 'test' If I have the regex: { name: /test/i } Is it possible to use the variable label inside the regex, in the following way? { name: `/${label}/i` } What do you think? ...

Taking out the z-index from the transition code

Is there a way to restructure the code without needing to use z-index for the transition? Without z-index: https://jsfiddle.net/Legcb42d/ .container1 { position: relative; width: 100%; height: 100%; } .container1.slide { height: auto; min-heigh ...

Vuetify - Implementing a search feature in a table that automatically navigates to the matching row

Currently, I am working with 2 Vuetify data tables that do not have pagination enabled. Each row in the second table corresponds to exactly one parent in the first table. My goal is to be able to click on an entry in the second table and have it automati ...

Problem with Angular 2 Typings Paths in Typescript

Currently, I am in the process of learning how to create a Gulp build process with Angular 2 and Typescript. Following the Quick Start guide has allowed me to get everything up and running smoothly. However, I have decided to experiment with different fold ...

Executing a JavaScript function without passing arguments does not yield the desired result

Within my JS file, I encountered an issue when trying to call one function from another. Initially, I called the function with no arguments using only its name handleResponse. However, when attempting to add arguments by changing the function signature, I ...

"Troubleshooting the malfunctioning of the String function with JSON data in Python

After retrieving data from an API, I converted it to a string in order to manipulate it using string operations. import urllib.request def f1(): strurl=urllib.request.urlopen("https://api.somedateapi.io") info=strurl.read() print(info) p ...

Adding Node.js Express responses to a running list

I have a situation in one route where I am using multiple instances of res.send. Is there a way to combine them all into one and then send the aggregated list at the end? The format I prefer is as follows: { "writer": {success message}, "archive": {succes ...

Is it possible to utilize a variable from a Higher Order Function within a different generation function?

I am facing a dilemma with the need to utilize email = user.email in newcomment['comments/'+id] = {id,comment,email,date}. However, I am unable to incorporate email = yield user.email or yield auth.onAuthStateChanged(user => {email = user.em ...

Setting a variable in Angular after a successful AJAX call

Working on a new small application and experimenting with Angular. Encountering an issue where I am making an AJAX GET request upon clicking a button. After receiving the response, I want to set a variable to hold the result, but for some reason the variab ...

Showcasing Items Within JSON Object in Angular

I am dealing with a JSON database that contains nested Objects: { "characters2": [ { "campaign":"Menagerie Coast", "index": 1, "name": "Mark Whithershmitz", "portrait": "assets/pics/markW.jpg", "affiliation": "Kryn Dynast ...

Clean coding techniques for toggling the visibility of elements in AngularJS

Hey everyone, I'm struggling with a common issue in my Angular projects: app.controller('indexController', function ($scope) { scope.hideWinkelContainer = true; scope.hideWinkelPaneel = true; scope.headerCart = false; scope. ...