arranging an array in JavaScript that contains numeric values stored as text

I'm attempting to organize my array. My goal is to sort the elements based on the value within the square brackets at index 2. This means that the element at position 15 should be at the top, followed by the one at position 8 and so forth.

I've made attempts using:

var sorted = data.sort(function(a,b){return b[2]-a[2]});
console.log(sorted);

as well as:

data.sort(function(a,b){return b[2]-a[2]});
console.log(sorted);

However, none of these methods seemed to work. Could it be due to the numbers being stored as text? If so, I also tried using:

data.sort(function(a,b){return parseFloat(b[2])-parseFloat(a[2])});
console.log(sorted);

but unfortunately, this didn't produce the desired result either.


0:(2) ["HDR", "GENERATION BY FUEL TYPE CURRENT Last Updated At 20180719150500"]
1:(2) ["FTR", "14"]
2:(8) ["FUELINSTHHCUR", "OCGT", "0", "0.0", "0", "0.0", "0", "0.0"]
3:(8) ["FUELINSTHHCUR", "OIL", "0", "0.0", "0", "0.0", "0", "0.0"]
4:(8) ["FUELINSTHHCUR", "COAL", "947", "3.0", "900", "2.9", "15144", "2.2"]
5:(8) ["FUELINSTHHCUR", "NUCLEAR", "6407", "20.4", "6477", "20.8", "158268", "22.5"]
6:(8) ["FUELINSTHHCUR", "WIND", "1710", "5.4", "1678", "5.4", "11903", "1.7"]
7:(8) ["FUELINSTHHCUR", "PS", "165", "0.5", "174", "0.6", "6854", "1.0"]
8:(8) ["FUELINSTHHCUR", "CCGT", "17355", "55.2", "17144", "55.1", "382043", "54.3"]
9:(8) ["FUELINSTHHCUR", "OTHER", "59", "0.2", "59", "0.2", "1406", "0.2"]
10:(8) ["FUELINSTHHCUR", "INTFR", "1998", "6.4", "1998", "6.4", "47363", "6.7"]
11:(8) ["FUELINSTHHCUR", "INTIRL", "0", "0.0", "0", "0.0", "1960", "0.3"]
12:(8) ["FUELINSTHHCUR", "INTNED", "1001", "3.2", "1000", "3.2", "23097", "3.3"]
13:(8) ["FUELINSTHHCUR", "INTEW", "0", "0.0", "0", "0.0", "4803", "0.7"]
14:(8) ["FUELINSTHHCUR", "BIOMASS", "1649", "5.2", "1621", "5.2", "48031", "6.8"]
15:(7) ["TOTAL", "31448", "100.0", "31128", "100.0", "703547", "100.0"]
16:(8) ["FUELINSTHHCUR", "NPSHYD", "157", "0.5", "77", "0.2", "2675", "0.4"]

Any assistance would be greatly appreciated.

Answer №1

If you need to sort non-given items to the top, you can use a large value like Infinity.

The Array#sort method requires a numerical value less than zero, zero, or greater than zero to determine the desired order. To achieve this, you can calculate the delta for simple numbers.

b - a // sorts in descending order

To handle an unused index of the array, you can check it using the in operator and assign a value that either shifts or retains the item at its current position on top by using a higher value than usual, such as Infinity.

var data = [["HDR", "GENERATION BY FUEL TYPE CURRENT Last Updated At 20180719150500"], ["FTR", "14"], ["FUELINSTHHCUR", "OCGT", "0", "0.0", "0", "0.0", "0", "0.0"], ["FUELINSTHHCUR", "OIL", "0", "0.0", "0", "0.0", "0", "0.0"], ["FUELIN...the following:
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Here's a simple solution

var sorter = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: 'base'
});
var numbers = ['1_Document', '11_Document', '2_Document'];
console.log(numbers.sort(sorter.compare));

Check out this helpful source

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

Formik's handleSubmit function seems to be being overlooked and not executed as

I've encountered an issue while trying to validate a form before submission using formik and yup validation. The form is divided into two parts, where the first part needs to be validated before moving on to the second part. I set a state handleShow(t ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

Update the text in a personalized dropdown menu when an option is chosen

After spending some time working on a customized dropdown with the use of CSS and Vanilla JavaScript (Plain JS), I encountered an issue while trying to select and update the dropdown text upon clicking an option: window.onload = () => { let [...opt ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...

Is it possible to filter JavaScript Array while ensuring that select options do not contain duplicate IDs?

I am utilizing two datatables with drag and drop functionality. Each row in the datatables contains IDs. When I drag a row from table 1 to table 2, the data is stored in an Array. I have an addArray function that pushes the IDs into the Array, filters out ...

Presenting JSON information in a concise and visually appealing manner

How can I extract a value from JSON data and display it in an HTML text field? The JSON data looks like this: {"name":"paul"}, but I only want to display "paul" in my text field. Here is my code in CodeIgniter PHP: $data['name'] = $this->name ...

Display a button only when hovering over it

Seeking assistance for a simple task that is eluding me at the moment. I am currently using scss and trying to make a button only appear when hovered over. The button is hidden in the code snippet below, nested within a block alongside some svgs. Any hel ...

Traverse through the nested JSON array using a loop

Exploring a JSON object: { "date_price": [ { "date": "Jan 2000", "price": 1394.46 }, { "date": "Feb 2000", "price": 1366.42 }, { "date": "Mar 2000", "price": 1498.58 }, { "date": "Apr ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

Issue encountered while generating a package using npm init in Node.js

I am currently in the learning process of NodeJs from tutorialspoint(TP). Following instructions provided in this link, I tried to create a package by running the following command: C:\Program Files (x86)\nodejs>npm init This utility will w ...

Is it possible to combine EJS compilation and html-loader in the html-webpack-plugin?

I need the html-webpack-plugin to generate my html using my .ejs template that contains <img> tags. The html-loader can update the image URLs in my <img> tags created by Webpack, so I am including it in my configuration: test: /& ...

What are the steps for implementing if-else statements in JavaScript when working with multiple dropdown lists?

I have encountered an issue while trying to display options in multiple drop-down lists. Only two words (CHENNAI AND IOS-XE, BANGALORE AND IOS-XR) are being displayed and the rest of the words are not appearing. Can someone provide assistance on fixing thi ...

Retrieving the IPv4 Address from an Express.js Request

I am currently working on setting up a whitelist for IP addresses in my API. However, when I use request.socket.remoteAddress in Express.js, I receive an IPv6 address (I believe) that looks like this: ::ffff:127.0.0.1. My main concern is how can I extract ...

Unlock the Potential of Spring REST-JWT-JavaScript for Seamless Transitions

In my Java Spring REST back-end, I am implementing a security feature using Json Web Tokens instead of sessions. For the front-end, I plan to use JavaScript and jQuery for sending requests to the back-end, along with HTML. After a successful login, I stor ...

What could be the reason for the absence of this modal?

I'm trying to create a modal that will be shown to users when they use the command modal. Can anyone help me troubleshoot this code? const { MessageActionRow, Modal, TextInputComponent } = require('discord.js'); client.on('interactionC ...

Guide for skipping the presentation of data in column1, when column2 contains multiple lines of content

How can I avoid showing redundant data for ItemA when ItemB has multiple lines to display: ItemA = [Color Fruit, Nuts] ItemB = [[green], [orange, apple, grapes], [cashew, almond]] if (this.point.customTT === 'Item') { ...

I am a beginner in the world of MEAN stack development. Recently, I attempted to save the data from my form submissions to a MongoDB database, but unfortunately, I have encountered

const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Schema = new mongoose.Schema({ username: St ...

What is the best way to display the Edit and Delete buttons in a single column?

Currently, I am encountering a small issue. I am trying to display Edit and Delete Buttons in the same column but unfortunately, I am unable to achieve that. Let me provide you with my code. var dataTable; $(document).ready(function () { dataTa ...

Sharing information between React components involves passing data as props. By sending data from

Brand new to React and still figuring things out. Here's the scenario: <div> <DropDown> </DropDown> <Panel> </Panel> </div> After selecting a value in the dropdown and storing it as currentL ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...