Why does Array Object sorting fail to handle large amounts of data in Javascript?

Encountered an issue today, not sure if it's a coding problem or a bug in Javascript. Attempting to sort an object array structured like this:

const array = [{
text: 'one',
count: 5
},
{
text: 'two',
count: 5
},
{
text: 'three',
count: 5
},
{
text: 'four',
count: 5
}]

Attempting to sort the object array based on the count index, using the following code:

Array.prototype.sortBy = function (p) {
          return this.slice(0).sort(function (a, b) {
            return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
          });
  }
   console.log(array.sortBy('count'))

Sorting works well for object arrays with less than 100 elements, but fails for larger arrays. Tried using some Npm packages as well without success. Any assistance would be appreciated.

Answer №1

There's no need to overcomplicate things, you can simply use the .sort method for this

Check out this codepen to see it in action with 500 elements for verification

const array = [{
    text: 'one',
    count: 3
  }, {
    text: 'two',
    count: 1
  }, {
    text: 'three',
    count: 2
  }, {
    text: 'four',
    count: 4
}];

let sorted = array.sort((a, b) => a.count - b.count);

console.log(sorted);

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

Unable to include the variable "$localStorage"

While working on my method in app.js, I encountered the following error: Uncaught Error: [$injector:strictdi] function($rootScope, $q, $localStorage, $location) is not using explicit annotation and cannot be invoked in strict mode http://errors.angula ...

Retrieving a specific data point from the web address

What is the most efficient way to retrieve values from the window.location.href? For instance, consider this sample URL: http://localhost:3000/brand/1/brandCategory/3. The structure of the route remains consistent, with only the numbers varying based on u ...

When using Angular, automatically shift focus to the next input field by pressing the

I am faced with a challenge involving multiple editable inputs on my screen. Alongside these editable inputs, there are buttons and disabled inputs present. The current behavior is such that when I press Tab, the focus shifts to the HTML elements between ...

Is it possible to create multiple text input components using the "each" function, and how can I update the state by combining all of them together?

I am looking to create a text-based word game where the length of each word changes with every level. Each letter will be placed in its own box, forming a matrix (e.g. 10 words, length: 10 => 10x10 matrix). How can I generate multiple text input compone ...

Cancelling measurements in Potree/three.js

Currently, I am utilizing Potree for the display of a large point cloud dataset, which can be found at https://github.com/potree/potree. I am attempting to initiate an area-measurement using Potree.MeasuringTool, which is typically stopped or accepted wit ...

I am experiencing difficulty with the button not responding when clicked, despite trying to implement JavaScript and the Actions syntax

Currently, I am in the process of automating form filling. After filling out the form, there is an update button that changes color instead of clicking when activated. This alteration indicates that the xpath is correctly identified. I have attempted two ...

Incorporating AngularJS and Bootstrap for seamless pagination experience

My JSON data looks like this: http://localhost:3001/images?page=1 {"images":[{"_id":"542e57a709d2d60000c93953","name":"image1","url":"http://www.syll.com","__v":0},{"_id":"542e58e19d237e5b790f4db2","name":"image154","url":"www.rufyge.com"},{"_id" ...

decide whether to use webpack bundling during development or not

Whenever I save a file, it takes around 30 seconds for the changes to reflect. I am currently using gulp watch and webpack for bundling around a hundred files. Is there any way to speed up the build process? ...

Arrangement of watch attachment and $timeout binding

I recently encountered a component code that sets the HTML content using $scope.htmlContent = $sce.trustAsHtml(content). Subsequently, it calls a function within a $timeout to search for an element inside that content using $element.find('.stuff' ...

My Angular2+ application is encountering errors with all components and modules displaying the message "Provider for Router not found."

After adding routing to my basic app through app.routing.ts, I encountered errors in all of my test files stating that no Router is provided. To resolve the errors, I found that I can add imports: [RouterTestingModule], but is there a way to globally impo ...

Add a unique identifier to a table row in a jQuery/AJAX function without the need for a looping structure

My PHP query retrieves client data and generates a table with rows for each client. Each row contains a link with a unique ID attached to it. Clicking on this link triggers an AJAX function based on the client's ID, which opens a modal displaying info ...

Determine the number of working days prior to a specified date in a business setting

How can I calculate X business days before a given date in JavaScript when I have an array of holidays to consider? I am currently thinking about using a while loop to iterate through the dates and checking if it is a business day by comparing it with the ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...

Delete a designated section from a URL with the power of jQuery

I have a URL like http://myurleg.com/ar/Message.html and I need to change ar to en in it when clicked on. For example, if my current URL is: http://myurleg.com/ar/Message.html After clicking, it should become: http://myurleg.com/en/Message.html I attemp ...

Avoiding Vue Select from automatically highlighting the initial option: tips and tricks

Currently utilizing Vue Select as a typeahead feature that communicates with the server via AJAX. By default, the first option from the server response is highlighted like this: https://i.stack.imgur.com/jL6s0.png However, I prefer it to function simila ...

There seems to be a glitch in my programming that is preventing it

Can someone please help me troubleshoot this code? I'm unable to figure out what's going wrong. The concept is to take user input, assign it to a variable, and then display a string. However, nothing appears on the screen after entering a name. ...

The issue with Array.prototype.join in Internet Explorer 8

In my current working scenario, I encountered an issue with the following code snippet. It performs well in the latest versions of Internet Explorer (IE), but the join function fails to work correctly in IE 8 Version. <!DOCTYPE html> <html xmlns= ...

Receiving array data in a Javascript function and storing it within a variable

Hello everyone, please take a look at my code below. I am attempting to pass PHP array values to a JavaScript function. When I run the script, I receive alerts for parameter0=1, parameter1=2, and parameter2=3 separately. What I am trying to achieve is to ...

There seems to be an issue with the hidden field value not being properly set within the

I created a function called getConvertionValue. Inside this function, I make an ajax call to the getCurrencyConvertion function in the controller. function getConvertionValue(from, to) { if (from != to) { $.ajax({ url: base_url + 'admin/o ...

Create a dynamic onClick event script and integrate it into Google Optimize

I need to incorporate a button element into my website using Google Optimize for an experiment. This button needs to trigger a specific script depending on the variation of the experiment. I have attempted two different methods: <button id="my-button" ...