Is Array.sort() ineffective when dealing with extensive arrays?

Why is Array.sort() failing on large arrays? Did I overlook something? I have double-checked to ensure that I'm not accidentally sorting strings. I'm struggling to comprehend why this is failing

Here is the code snippet I pasted from Chrome Debugger's Watch:

https://i.sstatic.net/VZmdS.png

Feel free to play around with this code:

arr = [1.238648000000012,1.5776880000000233,1.6462280000000078,10.007896000000017,10.014455999999996,10.016970000000015,10.018888000000004,10.028069000000016,10.047926000000018,10.056818000000021,10.057980999999984,10.075353000000007,10.086242000000027,10.088684999999998 ...

output = document.getElementById("output");
output.innerHTML += Math.max(...arr) + '<br />';
output.innerHTML += arr.sort()[arr.length-1] + '<br />';
output.innerHTML += arr.sort()[arr.length-2] + '<br />';
output.innerHTML += arr.sort()[0] + '<br />';

output.innerHTML += '---------------------------------------' + '<br />'

a = [1,2,3,0];
output.innerHTML += Math.max(...a) + '<br />';
output.innerHTML += a.sort()[a.length-1] + '<br />';
output.innerHTML += a.sort()[a.length-2] + '<br />';
output.innerHTML += a.sort()[0] + '<br />';
<html>
  <body>
    <div id='output'></div>
  </body>
</html>

Is it not expected for the last element in the sorted array to be the maximum value?

Answer №1

If you need to arrange numbers in ascending order, make sure to include a callback function. Omitting a callback will result in the numbers being sorted as strings, as mentioned on MDN

By default, the sort method converts elements to strings and then compares their UTF-16 code unit values.

var array = [1, 10, 100, 20];

array.sort((a, b) => a - b);
console.log(...array);

array.sort();
console.log(...array);

Important: The sort() function alters the original array. Be cautious when using it to avoid unexpected behavior, as it may cause issues in certain scenarios.

Answer №2

Using Math.max in this manner may lead to unreliable results as stated in the MDN documentation:

It is important to note that both spread (...) and apply methods may fail or produce incorrect results when the array contains a large number of elements. This is because they attempt to pass each array element as a function parameter. For more information, refer to the documentation on using apply and built-in functions. The reduce method does not suffer from this issue.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

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

The catch block seems to be failing to capture the errors thrown by the fetch API

I am facing an issue with my code where the fetch method, enclosed within a catch block, fails to capture errors. Despite attempting various error handling approaches on my node backend, the problem persists. https://i.stack.imgur.com/0reJj.png const e ...

Menu options are unresponsive to clicks in the dropdown

Need help fixing my dropdown menu issue. Whenever I hover over the dropdown, it disappears before I can click on any items. Here is a snippet of the code causing the problem: #navContainer { margin: 0; padding: 0; padding-top: 17px; width: 220 ...

Is there a way to refresh angular bindings using data retrieved from a getUserMedia stream?

I'm currently using getUserMedia to capture an audio stream. The audio stream is only accessible within the getUserMedia callback function. However, I have encountered an issue where Angular fails to detect changes and update the bindings when I attem ...

Error message "Exceeded the maximum call stack size" encountered during Vue-router authentication

I am currently in the process of developing a dashboard using Vue, Vuex, and Quasar. However, I have encountered an authentication error that is preventing me from progressing. Additionally, I need assistance in ensuring that when a user is already logged ...

Ways to extract metadata from a given URL

Recently, I've delved into the world of JavaScript and I'm looking to extract metadata from a given URL. Whenever a URL is entered into an input field, I want to retrieve its meta data - a simple task in HTML using JavaScript. However, every time ...

Issue arising from background change upon component focus

My component needs to change its background color when focused, but for some reason it's not working. The hover effect works fine, but the focus doesn't. Can anyone assist me with this issue? import { CardContainer } from './styles' in ...

Load a CSV document and add its contents to an existing array

My CSV file has a specific format: Image Id,URL,Latitude,Longitude 17609472165,https://farm8.staticflickr.com/7780/17609472165_c44d9b5a0e_q.jpg,48.843226,2.31805 11375512374,https://farm6.staticflickr.com/5494/11375512374_66a4d9af6c_q.jpg,48.844166,2.376 ...

Combining multer, CSRF protection, and express-validator in a Node.js environment

Within my node.js application, I am utilizing an ejs form that consists of text input fields in need of validation by express-validator, an image file managed by multer, and a hidden input housing a CSRF token (a token present in all other forms within the ...

Interacting with dynamically loaded HTML content within a div is restricted

On my main HTML page, I have implemented a functionality that allows loading other HTML pages into a specific div using jQuery. The code snippet looks like this: $('.controlPanelTab').click(function() { $(this).addClass('active').s ...

Naming axes in Chart.js is a simple process that can easily be implemented

Greetings to all, I'm currently working on creating bar charts using chartjs...everything is going smoothly except for one thing - I am struggling to find a clean way to name my axes without resorting to CSS tricks like absolute positioning. Take a ...

Modifying the color of a specific div using jQuery

I am attempting to develop a function that changes the background color of a div when a user clicks on it and then clicks on a button. The value needs to be saved as a variable, but I'm having trouble getting it to work because it keeps saying that th ...

Customizing the appearance and dimensions of JWPlayer Audio Player with percentage-based styling

I'm currently attempting to set up an audio embed using JWPlayer, following the instructions provided in this particular article. The article suggests setting it up with the following code: <div id="myElement">Loading the player...</div> ...

Comparison: executing an immediately invoked function expression (IIFE) and a separate

During my recent refactoring of some legacy code, I stumbled upon the following example: // within another function const isTriggerValid = await (async () => { try { const triggers = await db.any(getTriggerBeforeBook, { param ...

Tips for adding extra spacing between icon and text field using Vuetify

The code snippet below is used for the username section: <v-text-field prepend-icon="fas fa-user" height="60px" placeholder="Username" outlined ></v-text-field> Is there a way to add space between the user ...

Can Node.js fetch a PHP file using AJAX?

The Challenge: Greetings, I am facing an issue with my website that features a game created using node.js, gulp, and socket.io. The problem arises when I attempt to call a php file from node.js. While the file returns a success message (echo in the file) ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

How can I use a button created with jQuery's .html() method to conceal a <div>?

I am facing an issue with implementing a simple banner that should appear in an empty element only when specific values are returned by an Ajax call. In the banner, I want to include a Bootstrap button that hides the entire div when clicked. Due to my la ...

Dropzone.js only allows one audio file and one image thumbnail file to be uploaded simultaneously

Is there a way to limit the types of files that can be uploaded through Dropzone.js? Specifically, I want to restrict users to uploading only one image and one audio file. ...

Ways to expand a Bootstrap input field by clicking on it:

I have successfully created a search bar in my navbar, but I am looking to add functionality that allows the input field to expand to its normal size when clicked. I believe this will require some JavaScript implementation, however, I am unsure how to proc ...

A simple guide to fetching JSON data and storing it in a variable, then parsing it and displaying it

I am looking to retrieve JSON data from the Yahoo Finance API, store it in a JavaScript variable, extract specific information such as "name" and "price", and then display it in an HTML table. The JSON data can be accessed via the following link: Current ...