Can anyone recommend a speedy sorting algorithm for an extensive list of objects in JavaScript?

Struggling to organize a large array of 2000 elements in ReactJS using JavaScript. The array includes:

data = [

         {
    index: 0,
    id: "404449",
    product_name: "ette",
    brand_name: "Dyrberg/Kern",
    base_price: "55.000",
    actual_price: "55.000",
    filename:
      "http://images.booztx.com/dyrbergkern/400x523/329679_ette_sg_crystal.jpg",
  },
  {
    index: 1,
    id: "414661",
    product_name: "braided mobile chain",
    brand_name: "Octopus",
    base_price: "44.900",
    actual_price: "44.900",
    filename: "http://images.booztx.com/octopus/400x523/SC09-750MU.jpg",
  },

       ]

My attempt at sorting by base_price using Array.sort( ) is taking too long due to the size of the array. It currently takes about 4 minutes to sort all 2000 elements. Any suggestions on how to speed up this process?

Answer №1

The issue stemmed from a mistake in how imports were being used. Instead of importing the data as a constant, it should have been stored in a local variable to prevent any unintended changes when using array.sort( ). By updating the code to use a local variable for the sorted result, the problem was resolved.

import { data } from "assets/data/productList";

export const sortItems = (sortMode) => {
  const SortedData = data.sort((a, b) => {
    if (sortMode === SortModes[1].type) {
      return parseFloat(a.base_price) - parseFloat(b.base_price);
    } else {
      return parseFloat(b.base_price) - parseFloat(a.base_price);
    }
  });
  return SortedData;
};

Answer №2

It's worth noting that the process you're referring to shouldn't actually be time-consuming. For instance, when I ran a similar operation on my own machine with a 2000 element array, it took less than 10 milliseconds:

const generateRandomProduct = () => {
  const priceNumber = Math.random() * 100;
  const priceString = priceNumber.toFixed(3);
  return {
    index: 0,
    id: "54321",
    product_name: "hello universe",
    brand_name: "bar",
    base_price: priceString,
    actual_price: priceString,
    filename: "xyz456.jpg",
  }
}

const productsArray = [];
const totalElements = 2000;
for (let i = 0; i < totalElements; i++) {
  productsArray.push(generateRandomProduct());
}


const initialTime = Date.now();
productsArray.sort((a, b) => {
  return parseFloat(a.base_price) - parseFloat(b.base_price);
});
console.log(`Time taken: ${Date.now() - initialTime} milliseconds`);

There might be some other factor affecting the performance of this operation beyond what you've mentioned here.

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

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

Tips on preventing users from navigating backwards in a React Redux application

Seeking guidance on how to restrict user access after successful login in react redux. Can anyone assist me? I want to prevent users from navigating back to certain routes once they are logged in I am currently working on securing the routes to block unau ...

Step-by-step guide on loading an external javascript file once a webpage is fully loaded, and incorporating a function from it

After the initial page load, I have a need to incorporate an external JavaScript file into an HTML file. This is necessary because a variable in this external JS file only updates after the HTML file has fully loaded. Additionally, I want to utilize the fu ...

What is the best way to send a variable using $.post in a JavaScript script?

My jQuery and Javascript code below is responsible for handling the ajax request: else { $.post("http://www.example.com", {email: val}, function(response){ finishAjax('email', response); }); } joi ...

Retrieve a targeted table from a webpage through Ajax refresh

On a webpage, I have a table that has two different views: simple and collapsible. I want to be able to toggle between these views using a button click without the need to refresh the entire page. Below is the code snippet I am currently using: $(&apo ...

The current enablement status does not support the experimental syntax 'flow' (7:8):

Utilizing a Mono repo to share react native components with a react app has presented some challenges. When attempting to use a react native component from react, an error keeps popping up that I can't seem to resolve. I've attempted to follow t ...

The redirect feature in getServerSideProps may not function properly across all pages

Whenever a user visits any page without a token, I want them to be redirected to the /login page. In my _app.js file, I included the following code: export const getServerSideProps = async () => { return { props: {}, redirect: { des ...

Ways to align DataGrid columns to begin from the right in Material UI

In my project, I am using a data-grid of Material UI and I am looking to adjust the style so that all columns align from right to left. Each column should start on the right side. You can view the code on this sandbox. ...

Establishing the controller to set the default order

Would appreciate some assistance with what may appear to be a beginner's question, please? This is the HTML code I'm working with: <!doctype html> <html> <head> <title>Starting Angular</title> </head> < ...

The state is not being configured accurately

In my ReactJs project, I have a model Component with a picture that is displayed. I want to pass the data of the clicked picture, which can be neither raw data nor a URL. I have implemented a handler that can delete the picture (if pressed with the Ctrl k ...

Having trouble with protractor's sendKeys function when trying to interact with md-contact-chips

Does anyone know how to set a value using sendKeys in Protractor for md-contact-chips? I attempted to use element(by.model('skills')).sendKeys('Java'); but it doesn't seem to be working. Any suggestions on how to approach this in ...

React.js not displaying image

Here's my App.js File I am trying to display an image from the MongoDB database. Click here to view the image stored in MongoDB The images are stored as Binary data in MongoDB How can I display the image on the React page? import React,{useState} fr ...

React Redux returning boolean values

Having two actions is essential for controlling a menu in my application. One action closes the menu (using false) and the other action opens it (using true). I've initialized the value to true in my reducer. import { OPENED_MENU,CLOSED_MENU } from & ...

Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response. There are 3 tasks I need to accomplish here:- Calculate the word count in the document. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech. A ...

Update input box value using Javascript

Here is the code for a <script> tag on a webpage that includes an input box within the body of an HTML document- <script type="text/javascript" language="JavaScript"> window.onload = function addSearchText() { document.getElementB ...

Instructions for manipulating and displaying a source array from a child component using Vue

I have a parent component with an array that I display in the template. My goal is to click on a link that uses vue-router with a dynamic id attribute, and then open a new component displaying only the element of the array that corresponds to that id. Howe ...

What is the best way to convert a JSON object into a string containing a negative zero in JavaScript?

Is there a way to properly convert a negative zero into a string using JSON.stringify? I've noticed that JSON.stringify often converts negative zero into a positive one, which is not the desired outcome. Any suggestions for an alternative approach? v ...

Is it feasible to maintain a persistent login session in Firebase without utilizing the firebase-admin package through the use of session cookies?

Currently, I am integrating Firebase into my next.js application for user login functionality. The issue I am facing is that users are getting logged out every time they switch paths within the site. Even though their session cookie has not expired, if the ...

What steps can be taken to ensure a user remains logged in even after a page reload in a Next.js app utilizing Firebase authentication?

I have implemented Firebase authentication for user login using GoogleAuthProvider. However, I am encountering an issue where the user gets logged out on page reload. Is there a way to persist the user without storing any credentials in localStorage? Belo ...

Having trouble with playing audio from an array in Javascript

I've been working on creating a Drum Kit website. My approach involves using an array to hold all the sound files, and using a loop to call the play() function. However, I encountered an issue when trying to load the sounds - the debug console showed: ...