Reputation: 123
I am attempting to sort my topArr.sales
from Greatest to Least.
I am using the .sort()
method in order to try and accomplish this.
At the moment my console.log
return value is identical to the original array and I am stuck on what I am doing wrong in order to accomplish my desired result.
My expected result is having the topArr
return in order, from greatest to least. Here is am example of my desired result:
let topArr = [
{ sales: "494,927", store: "Online" },
{ sales: "418,883", store: "Walk in" },
{ sales: "48,883", store: "Retail Stores" },
{ sales: "28,883", store: "Appointments" },
]
Here is my code snippet:
let topArr = [
{ sales: "494,927", store: "Online" },
{ sales: "48,883", store: "Retail Stores" },
{ sales: "418,883", store: "Walk in" },
{ sales: "28,883", store: "Appointments" },
];
topArr.sort(function (a, b) {
return a.sales - b.sales;
});
console.log(topArr)
Upvotes: 2
Views: 663
Reputation: 5786
Your sales is in form of a string. You need to first parse it into an integer before you can pass it to the sort's compare function.
You can try doing it as follows -
let topArr = [{
sales: "494,927",
store: "Online"
},
{
sales: "418,883",
store: "Walk in"
},
{
sales: "48,883",
store: "Retail Stores"
},
{
sales: "28,883",
store: "Appointments"
},
]
topArr.sort(function(a, b) {
var str1 = a.sales; //Taking the string a.sales into a string variable
var str2 = b.sales;
str1 = str1.replace(/[^\d\.\-]/g, ""); //removing the commas
str2 = str1.replace(/[^\d\.\-]/g, "");
return parseInt(str1) - parseInt(str2); //parsing the modified string into float and comparing them.
});
console.log(topArr);
One more thing to note is I have assumed that sales stores only integer values. If some sales store float as well, use - parseFloat(str1) > parseFloat(str2)
to get the right output.
*Note - If the above replace statement isn't working, you can also try -
str1.replace(/,/g, "");
Upvotes: 3
Reputation: 5162
You need to change the comparator function to use numeric values instead of string.
let topArr = [
{ sales: "494,927", store: "Online" },
{ sales: "48,883", store: "Retail Stores" },
{ sales: "418,883", store: "Walk in" },
{ sales: "28,883", store: "Appointments" },
];
topArr.sort(function (a, b) {
return parseInt(a.sales.replace("/,/g","")) - parseInt(b.sales.replace("/,/g",""));
});
console.log(topArr)
Upvotes: 2