Sort an array in descending order based on the key using JavaScript in Google Chrome

Having an issue with sorting an array in descending order by the key. It works perfectly in Firefox, but Chrome is displaying it in the original order.

[["0", 0], ["1", 0.9], ["2", 597.5344192965547], ["3", 991.0326954186761], ["4", 1257.2580315846578], ["5", 1293.5250901880618], ["6", 2197.1091224116512], ["7", 2225.0422585266947], ["8", 3964.1307816747044], ["9", 6914.072436146399]]

This is the function I'm using:

sortable.sort(function(a,b){return b-a})

Firefox returns the correct result:

[["9", 6914.072436146399], ["8", 3964.1307816747044], ["7", 2225.0422585266947], ["6", 2197.1091224116512], ["5", 1293.5250901880618], ["4", 1257.2580315846578], ["3", 991.0326954186761], ["2", 597.5344192965547], ["1", 0.9], ["0", 0]]

However, Google Chrome doesn't sort the array as expected.

Answer №1

Your task involves sorting an array of arrays where the outer array is labeled as "sortable." The issue arises when your sorting function uses the subtraction operator on array instances. For example, when calling the `sort` method, you may end up comparing arrays like `["0", 0]` and `["1", 0.9]`. This comparison looks like this within the function:

return ["0", 0] - ["1", 0.9];

By using the `-` operator on these operands, JavaScript attempts to convert them into numbers, often resulting in `NaN`. And since subtracting two `NaN` values also results in `NaN`, it violates the expected behavior of a sorting comparator callback.

To address this issue, it seems you want to sort based on the first element of each inner array. To achieve this, you can modify your sorting function as follows:

sortable.sort(function(a,b){return b[0]-a[0]})

(Notice the `[0]` after each array reference.) This adjustment ensures that the strings representing the first elements are converted to numbers before the subtraction operation takes place. Alternatively, you could explicitly convert these strings to numbers with a specific radix:

sortable.sort(function(a,b){return parseInt(b[0], 10) - parseInt(a[0], 10)})

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

Enable automatic scrolling for CSS overflow: scroll feature

I am currently developing a chat application where messages are displayed in a background. I have used CSS to add an overflow scrollbar with the line overflow-y: scroll;. Everything is working properly, but I'm wondering if there is a way to automatic ...

Guide on retrieving a file through an HTTP request with restricted cross-origin access restrictions

Having some issues with downloading files from specific links, such as . My goal is to automate the download process for these redirected files. The challenge I'm facing is that trying to access the link directly through a web browser just gives me a ...

Using Jquery to load Intranet HTML files

My current project involves creating a system for users to access a specific application on the work intranet. The setup consists of directing them to a splash index.html page containing links that lead to various network drives, some accessible only to ce ...

Using JavaScript to link buttons and dynamically change their colors

Just starting to dabble in JavaScript and attempting to change the colors of my website's header, footer, and background. I've created two buttons: <div class="styleBut"> <a href="#" class="btn btn-warning">ReStyle</a> ...

An Illustrative Example of Inheritance in Javascript?

I've been searching on various platforms for a straightforward example of inheritance without much luck. The examples I've come across are either too complex, obscure, or just not user-friendly. I have multiple service functions that all share so ...

Creating a custom titlebar with Electron and Vue: How to accurately determine the window's maximized or restored state from within a component

Currently, I am working on a frameless application that incorporates a custom titlebar (Electron + Vue + Vuex, with the electron-vue boilerplate). I have successfully implemented functionality to toggle the maximize/restore buttons upon click. The issue a ...

Mastering the use of expressions in ng-click and ng-show in AngularJS

I've been working on creating expandable rows within a table, but I'm encountering some issues. Despite not receiving any error messages, the functionality isn't behaving as expected. I suspect there might be an issue with how I'm using ...

Seeking further clarification on the topic of `custom Directive` in AngularJS

Implementing a login form in my application, I have chosen to display errors on blur of the input element. Although this approach works, I have encountered several questions regarding a custom directive I created without thorough explanation from the tuto ...

Is there a technique I could use to create a visual effect like zooming, but without altering the dimensions of the image?

I'm currently working on a project to develop a photo gallery. let img = document.createElement('img') img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Wikipedia_logo_%28svg%29.svg/1250px-Wikipedia_logo_%28svg% ...

As the window size decreases, adjust the negative left margin to increase dynamically

Is there a way to adjust the margin-left property of mydiv-2 to become increasingly negative as the browser window is scaled down horizontally? #mydiv-1{ background-color:orange; width:60%; height:400px; margin-left: 150px } #mydiv-2{ backgr ...

Async function captures error being thrown

I am looking to implement an async function in place of returning a promise. However, I've run into an issue with rejecting using error throwing: async function asyncOperation() { throw new Error("Terminate this application."); } (async () => { ...

When using Laravel with jQuery Ajax, the search for the file address is unsuccessful

Learning Laravel has been a challenging journey for me. I've encountered numerous problems that have made it feel like more of a hindrance than a helpful tool. But the real story lies elsewhere. Working with Laravel 4 and jQuery 2, I attempted to fet ...

I'm looking to leverage useEffect in React Native to effectively manage and store arrays - any tips on how

Redux has provided me with data called targetFarm, which contains an array of objects in targetFarm.children. targetFarm.children = [ {name: 'pizza'}, {name: 'burger'}, {name: 'lobster'}, {name: 'water'}, ] I am try ...

What is the method for determining the coordinate range in a three.js environment?

When developing a scene using html and javascript, incorporating a camera, renderer, and displaying the scene in a browser, how can one determine the visible range of the scene? In a specific scenario where only a 2-dimensional x/y scene with objects is b ...

What are some best practices for utilizing `element.offsetParent` in HTML SVG elements?

I'm currently updating some JavaScript code that relies on the .offsetParent property. The recent changes in the application involve the use of SVG elements, which are causing issues with the JavaScript as mySvgElement.offsetParent always returns unde ...

Navigating through a JSON dictionary in Svelte: A step-by-step guide

When working with Svelte, the #each construct allows for easy iteration over array-like objects. But what if you have a JSON dictionary object instead? Is there a way in Svelte to iterate over this type of object in order to populate a dropdown menu? The ...

Troubleshooting: My jQuery script for fading in content upon document ready is not

I'm currently working on a website where I want everything to fade in when the user enters the site. Take a look at my code: var celyLogin = $(".container"); $(document).ready(function () { /*! Fades in page on load */ $("container") ...

Resolving the problem of degrading image quality in HTML Canvas

Recently, I came across an issue while trying to display graphics on an HTML page using canvas. The problem I encountered was that the canvas element was somehow reducing the quality of my images during rendering, especially after some time. Let me visual ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...

Verify and generate a notification if the value is null

Before saving, it is important to check for any null values and alert them. I have attempted to do so with the following code, but instead of alerting the null values, the data is being saved. . function fn_publish() { var SessionNames = getParamet ...