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

VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs. Continuously encountering these two errors: [Vue warn]: Error in mounted hook: "TypeError: Cann ...

Swap Text Inside String - JS

I have a challenge where I need to extract an ID from an HTML element and then replace part of the extracted word. For instance: HTML <input type="checkbox" id="facebookCheckbox"></div> JavaScript var x = document.getElementById("facebookCh ...

VisualMap in ECharts featuring multiple lines for each series

If you'd like to view my modified ECharts option code, it can be found at this URL: Alternatively, you can also access the code on codesandbox.io : https://codesandbox.io/s/apache-echarts-demo-forked-lxns3f?file=/index.js I am aiming to color each l ...

What could be causing the failure of this web component using shadow DOM when the HTML code includes multiple instances of the component?

Recently, a question was raised on this platform regarding the use of Selenium to access the shadow DOM. Curious about this topic, I delved into the MDN article Using shadow DOM and decided to replicate the code on my local machine. Surprisingly, it worked ...

How can a JavaScript code be used to navigate to a different HTML file within the same directory that is stored within a folder?

Here is the sample HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewpor ...

Parsing JSON data using PHP and AJAX decoding

I have been searching for a way to pass parameters between the server and client, but I am struggling to find a solution that works. Despite reading extensively online, I have not been able to come up with a functioning solution. Client Side function sen ...

Clicking on Google Code Prettify does not trigger syntax highlighting

I utilize Google Code Prettify for syntax highlighting my code. Below is the HTML snippet I use: <head> <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script> </head> <body> ...

When utilizing div.load, jQuery and other JavaScript sources may not be defined

When you load a page using jQuery load: $("#myDiv").load("page.php",{foo: bar}); The head section is included in the index: <head> <script src="/assets/plugins/jQuery/jQuery-2.1.4.min.js"></script> <script src="/assets/plugi ...

Enhancing TypeScript with Generic Proxyify Functionality

I'm attempting to enclose a basic interface provided through a type generic in order to alter the return value of each function within the interface. For instance: interface IBaseInterface { test(a?: boolean, b?: number): Promise<boolean>; ...

The button must be programmed to remove a specific item from the server

I am currently developing an application to monitor my expenses using javascript, nodejs, express, and handlebars as the templating engine. Within the app, I have a "list" div that displays all of my expenses. (There is an add button next to the list, not ...

Updating className in React by responding to button clicks without relying on numerous conditional statements

I've been working on a small project for the past few weeks. The main idea is to have a stepper with different steps that the user can click on to see their tasks for each step. There is also a completion button for each step, but I'm struggling ...

How can one transform a json object into a json string and leverage its functionalities?

I recently encountered an issue with a JSON object that contains a function: var thread = { title: "my title", delete: function() { alert("deleted"); } }; thread.delete(); // alerted "deleted" thread_json = JSON.encode(thread); // co ...

Ways to implement dark mode in Next.js version 13.4.10

In an attempt to incorporate a dark-light mode feature into my Next.js app version 13.4.10 without relying on the next-theme package, I encountered a challenge. My goal is to initially check for a selected mode in cookies or storage, and if not available, ...

Is there a solution to resolving the hydration UI error in next.js when utilizing the use-sse hook?

I have implemented use-sse (server-side rendering hook) in my next.js application, but I keep encountering an error stating "There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to clien ...

Utilize Javascript ES6 to Sort Through Data in a Table

I require assistance with my project using Material UI and React. There are two key implementations that I need: I am looking to create a filtering system for all rows in each column as shown in the attached image. Additionally, I need a button that can a ...

Out of the blue div, could you lend your assistance?

I have a code that displays 5 random images with corresponding text. My challenge is that I want to separate the text into another div so that I can add another function to it, while still keeping the images random with their corresponding text. <scr ...

How can I ensure that the appropriate 'this' is accessed within a callback function for an AJAX request?

When working with a callback function, I am having trouble accessing this. Instead, it seems to be pointing to the AJAX object rather than the object that initially invoked the onClickEmail function. I attempted to store a reference in a variable called th ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

Sending form data to PHP script following Javascript verification

After implementing basic validation for a contact form, I encountered an issue where the form would not submit to the PHP file responsible for sending emails. Despite setting the button type as "submit" and defining the form action as "contactform.php", th ...

Transforming an array of strings to integers within a GraphQL query when they are incorporated

I need help finding a solution to pass an array of strings and embed it into a query while using React and GraphQL. The issue I'm facing is that even though the parameter is accepted as an array of strings, it gets converted to a string when embedded. ...