Currently, I am working on a feature to sort an array of objects based on user-selected values. Strangely, the function returns the same result no matter which case is executed. I have thoroughly checked each case and they are functioning correctly; however, the sorting function seems to be malfunctioning.
This task is part of my development work on a Next.js application where I trigger the sorting operation within the useEffect hook every time the sortBy value changes.
const x = [
{
timestamp: 1000,
fairity: 1,
communication: 3,
manners: 3,
location: 2,
price: 5,
overall: 4
},
{
timestamp: 234,
fairity: 4,
communication: 2,
manners: 4,
location: 1,
price: 1,
overall: 1
},
{
timestamp: 23432,
fairity: 4,
communication: 1,
manners: 2,
location: 1,
price: 4,
overall: 3
},
]
const sortByOptions = {
DATE_ASC: 'DATE_ASC',
DATE_DESC: 'DATE_DESC',
LANDLORD_ASC: 'LANDLORD_ASC',
LANDLORD_DESC: 'LANDLORD_DESC',
PROPERTY_ASC: 'PROPERTY_ASC',
PROPERTY_DESC: 'PROPERTY_DESC'
};
const sortReviews = (_reviews, by) => {
console.log('asc', _reviews.sort((a, b) => a.timestamp - b.timestamp))
console.log('desc', _reviews.sort((a, b) => b.timestamp - a.timestamp))
switch (by) {
case sortByOptions.DATE_ASC:
return _reviews.sort((a, b) => a.timestamp - b.timestamp);
case sortByOptions.DATE_DESC:
return _reviews.sort((a, b) => b.timestamp - a.timestamp);
case sortByOptions.LANDLORD_ASC:
return _reviews.sort((a, b) => (a.manners + a.fairity + a.communication) - (b.manners + b.fairity + b.communication));
case sortByOptions.LANDLORD_DESC:
return _reviews.sort((a, b) => (b.manners + b.fairity + b.communication) - (a.manners + a.fairity + a.communication));
case sortByOptions.PROPERTY_ASC:
return _reviews.sort((a, b) => (a.location + a.price + a.overall) - (b.location + b.price + b.overall));
case sortByOptions.PROPERTY_DESC:
return _reviews.sort((a, b) => (b.location + b.price + b.overall) - (a.location + a.price + a.overall));
default:
return [];
}
};
console.log(sortReviews(x, sortByOptions.DATE_DESC))