I have some Objects stored in an Array.
const products = [
{
title: "Gigabyte GeForce RTX 2060 OC",
originalPrice: 329.99,
discountPrice: 292.77,
discountAmount: "11.28%"
},
{
title: "Gigabyte GPU NV RTX2060 Windforce OC 6GB Fan",
originalPrice: 349.99,
discountPrice: 306.99,
discountAmount: "12.29%"
},
{
title:
"ASUS Dual GeForce RTX 2060 OC EVO Edition 6GB GDDR6 Gaming Graphics Card with Two Powerful Axial-tech Fans (DUAL-RTX2060-O6G-EVO)",
originalPrice: 319.98,
discountPrice: 312.99,
discountAmount: "2.18%"
}
];
I am trying to sort the Array based on the Objects discountAmount property. I have spent the last hour trying solutions here on StackOverflow but nothing has successfully sorted the Array, the Objects remain in the same position. I have included two of my solutions to this problem below.
Solution 1:
products.sort((a, b) => {
const prodA = parseFloat(a["discountAmount"].replace(/%/, ""));
const prodB = parseFloat(b["discountAmount"].replace(/%/, ""));
if (prodA > prodB) comparsion = 1;
else if (prodA < prodB) comparsion = -1;
else return 0;
});
Solution 2:
function compareValues(key, order = "asc") {
return (a, b) => {
// Just Checking if The Key Exists
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
return 0;
}
let prodA = typeof a[key] === "string" ? a[key].toUpperCase() : a[key];
let prodB = typeof b[key] === "string" ? b[key].toUpperCase() : b[key];
prodA = prodA.replace(/%/, "");
prodB = prodB.replace(/%/, "");
let comparison = 0;
if (prodA > prodB) comparsion = 1;
else if (prodA < prodB) comparsion = -1;
return order === "desc" ? comparison * -1 : comparison;
};
}
Apologies in advance if there is a clear misunderstanding here.
%you have to turn the values into numbers before comparing themcomparisonconsistently ("comparsion")undefinedor zero.a[key]/b[key]but in the next line you just assume that they are always strings (or anything with a.replace()method that accepts a regular expression and a string) - so why test them in the first place?