I have been trying to sort an array with 2000 elements in ReactJS using JavaScript. The array looks like this:
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",
},
]
I tried sorting it by base_price with Array.sort( ) of JavaScript, like this:
data.sort((a, b) => {
return parseFloat(a.base_price) - parseFloat(b.base_price);
});
but since the array is very long, it has 2000 elements it takes a very long time to sort. It takes about 4 minutes. Does anyone have any solutions?
As mentioned in the comments, what you're describing should not actually take very long. Here's an example, and on my machine I'm seeing less than 10 milliseconds of runtime for a 2000 element array:
const createFakeProduct = () => {
const priceNumber = Math.random() * 100;
const priceString = priceNumber.toFixed(3);
return {
index: 0,
id: "12345",
product_name: "hello world",
brand_name: "foo",
base_price: priceString,
actual_price: priceString,
filename: "abc123.jpg",
}
}
const data = [];
const len = 2000;
for (let i = 0; i < len; i++) {
data.push(createFakeProduct());
}
const before = Date.now();
data.sort((a, b) => {
return parseFloat(a.base_price) - parseFloat(b.base_price);
});
console.log(`elapsed: ${Date.now() - before} milliseconds`);
There must be something additional thing besides what you've shared that's slowing it down.
It turns out that the problem was using imports incorrectly. I imported the data as a constant, but array.sort( ) was trying to change it. I used a local variable for the result of sort and that fixed the problem.
import { data } from "assets/data/productList";
export const sortItems = (sortMode) => {
const SoretdData = 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 SoretdData;
};