The sorting function is failing to produce the expected order of values

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))

Answer №1

After some trial and error, I came to the realization that my usage of the sort function was incorrect. It dawned on me that instead of returning a value, the sort function actually mutates the provided array. To address this issue, I made adjustments to my implementation so that it executes correctly during the mapping process.

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 sortByFunctions = {
    DATE_ASC: (a, b) => a.timestamp - b.timestamp,
    DATE_DESC: (a, b) => b.timestamp - a.timestamp,
    LANDLORD_ASC: (a, b) => (a.manners + a.fairity + a.communication) - (b.manners + b.fairity + b.communication),
    LANDLORD_DESC: (a, b) => (b.manners + b.fairity + b.communication) - (a.manners + a.fairity + a.communication),
    PROPERTY_ASC: (a, b) => (a.location + a.price + a.overall) - (b.location + b.price + b.overall),
    PROPERTY_DESC: (a, b) => (b.location + b.price + b.overall) - (a.location + a.price + a.overall)
  };


reviews.sort(sortByFunctions[sortBy]).map((x, i) => (...));

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

Utilize Express.js routes to deliver static files in your web application

I am looking to serve a collection of HTML files as static files, but I want the routes to exclude the .html extension. For example, when someone visits example.com/about, I'd like it to display the contents of about.html In my research on serving ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

Stop iScroll from scrolling the listview filter

I have been working on integrating iScroll into my application using the javascript-jquery.mobile.iscroll plugin. My goal is to apply it to enable scrolling for a listview component on a specific page while keeping the filter fixed just below the header, a ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

When using window.location.href and location.reload(), the updated page content from the server is not loaded properly

Currently, I am working on a form that is being updated via an AJAX call. Once the AJAX call successfully completes, I want to reload the page in order to display the new changes. Even though I tried using location.reload() and window.location.href after ...

Having trouble implementing font css file in Reactjs

When working with Reactjs (Nextjs), every time I try to incorporate "css" into my project, I encounter the following error on my screen: Module not found: Can't resolve '../fonts/fontawesome-webfont.eot?v=4.7.0' How can I solve this issue? ...

What is the method to implement timeago.js?

I've recently embarked on my journey to learn JavaScript, and it has only been two weeks since I started. As a beginner, I'm encountering some difficulties with implementing timeago from . The specific line of instruction that's giving me tr ...

Utilize AngularJS to integrate a service into the router functionality

What is the best way to inject a service into my router so that its JSON result will be accessible throughout the entire application? Router: export default ['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterP ...

Implementing a node.js application deployment with pm2 to ensure zero downtime

While there are countless tutorials on developing chat applications using socket.io and node.js, the event-driven advantage of Node is undeniable for building chat apps. However, a recent thought crossed my mind - how can I ensure the sustainability of my ...

Exploring the documentation of JQuery's $.Ajax Function

Can anyone help me locate the parameters in the JQuery Docs? jqXHR.done(function( data, textStatus, jqXHR ) {}); http://api.jquery.com/deferred.done/ I've been trying to determine what data represents but haven't had any luck. I've notic ...

Execute JavaScript script once when route changes

I'm currently working on a system where I want to ensure that my animation-based JavaScript code only runs once after the route changes. The issue I'm facing is that when switching between pages and returning to the about page, the scripts are ca ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

React Router: Dispatch not triggering when route changes

I have multiple paths that share the same controller: <Route component={Search} path='/accommodation(/:state)(/:region)(/:area)' /> and when the route changes, I trigger the api function within the component: componentWillReceiveProps = ...

Problem with sortable columns in DataTables

$(document).ready(function () { var dt = $('#example').DataTable({ "processing": true, "serverSide": true, "ajax": "api.php?t=clients", "columns": [{ "className": "details-control", ...

Transferring files and information using the Fetch API

I am currently working on a React application and I have defined the state of my application as shown below: const [book, setBook] = useState({ title: '', cover: {} numberPages: 0, resume: '', date: date, }); The & ...

What could be causing my handle button to slide off the timeline towards the right?

I'm facing an issue with my volume bar component where the slider button is rendering outside of the timeline instead of on top of the progress bar. I need assistance in adjusting its position. // Here is the code for my volume bar component: import ...

The NEXT.js API endpoint is not configured to handle POST requests

I am having an issue with my Next.js API route located at "pages/api/contact". The API appears to be working when I process a GET request or navigate to localhost:3000/api/contact. However, when attempting to process a POST request to this API ro ...

Discovering a website's console content using the "web-request" npm package

I recently added the web-request NPM package to my project with the goal of retrieving console messages from a specific website. However, I encountered an issue as I was unsure of how to achieve this. var result = await WebRequest.get('http://disco ...

Tips for incorporating a list into a MongoDB query

I encountered a problem with my dynamic queries when using an array for the column value. For example, if col is an array like c("red", "blue"), the query fails to execute. Works fine with single value col<-"red" pipe1 <- paste("{&bsol ...