Arranging a list based on additional factors

I'm struggling to grasp the functionality of the Array.sort method. In my case, I have an array structured as follows:

[
  {
    "votes": 3,
    "suggestedDate": "2019-12-01T01:13:00.978Z"
  },
  {
    "votes": 1,
    "suggestedDate": "2020-05-14T21:55:05.879Z"
  },
  {
    "votes": 1,
    "suggestedDate": "2019-12-01T03:22:40.848Z"
  }
]

Currently, I am utilizing

things.sort((a, b) => b.votes - a.votes)
. However, this order appears random when votes are equal. Can anyone recommend a sort function that will ensure a stable and date-based order in such scenarios?

Answer №1

How can I achieve a stable, date-based order when votes are equal?

To maintain a consistent ordering based on dates when the number of votes is the same, you can customize the existing array.sort callback function by considering both the votes and suggestedDate parameters.

const things = [{
    "votes": 3,
    "suggestedDate": "2019-12-01T01:13:00.978Z"
  },
  {
    "votes": 1,
    "suggestedDate": "2020-05-14T21:55:05.879Z"
  },
  {
    "votes": 1,
    "suggestedDate": "2019-12-01T03:22:40.848Z"
  }
]

things.sort((a, b) => {

  if (b.votes === a.votes) {
    return new Date(b.suggestedDate) - new Date(a.suggestedDate)
  }

  return b.votes - a.votes

})

console.log(things);

Also, take a look at this related question that @John mentioned

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

Accessing a JSON file from a nearby location using JavaScript

I am currently working on an artistic project based on weather data, which will be hosted locally with the JSON file updating via FTP synchronization. This means that the JSON file will be sourced from the same computer where it is stored. The code snippet ...

AngularJS: Changes to the model do not automatically reflect in the view

Currently, I am developing a web-based Twitter client using Angular.js, Node.js, and Socket.io. Tweets are pushed to the client via Socket.io, where a service listens for new tweets. When a new tweet arrives, the service triggers an event using $broadcast. ...

Changing the color of a text box when it is disabled can be achieved through JavaScript

I'm facing an issue with the formatting of my HTML elements. Specifically, I have 2 combo boxes and one text box in which all 3 are disabled. However, when they are disabled, the background color of the text box does not match that of the combo boxes. ...

Instructions on finding and inputting text into a textarea using python and javascript

Hello there, I've been experimenting with writing text inside a textarea element using Python Selenium and JavaScript: The JavaScript code I'm using is: self.driver.execute_script("document.getElementsByClassName('textarea').value ...

Save information from pop-up window to storage

I've encountered an issue with displaying a form on a popup window triggered by the "Add" button. I'm using a modal to show a PHP form, but when attempting to save the input data into the database, it's not functioning correctly. Upon clicki ...

React Native's NativeBase checkbox component: Overlapping text causing the content to extend beyond the confines of the screen

I am having trouble getting the text inside a checkbox (using nativebase) to shrink. Does anyone know why this is happening? Do I need to add some flex properties? import React from "react" import {Box, Center, Checkbox, Heading, NativeBaseProv ...

SQL UPDATE event not functioning properly when triggered by Discord.js via message event

I've been grappling over the past few days to successfully implement an SQL UPDATE event in discord.js using the mysql npm package. I have meticulously checked all login details, table names, and column names, but still can't get it to work as in ...

Eliminating Matching Elements from Pair of Numpy Arrays

I'm facing a seemingly simple question that I can't seem to find an answer for online. In my data, I have arrays of flux values and corresponding time values. While these two arrays are directly related (one flux value for each time value), some ...

Generate inputs from terminal and store them in a collection

Is there a way to save command line arguments and their parameters in separate arrays without knowing the number of ":" used? For example: ./run cat hello.txt : grep left : wc -c I want to divide each argument into an array, like: char *cat_args[] = {"ca ...

Why does the click on the download link result in the image opening instead?

I'm having an issue with my code that is supposed to download a file, but instead it opens the file. What am I doing wrong? <html> <body> <p>Click on the Image to download the image:<p> <a href="/website/image1.jpg" downl ...

Tips for preventing JavaScript errors when making cross-domain requests using AJAX

Is there a way to prevent or handle JavaScript errors without causing the script to crash? Error message: No data returned $.ajax({ type : 'GET', dataType : 'jsonp', url : '//cvrapi.dk/api?search=dsfsdfsd&country= ...

Is smooth scrolling consistent across all web browsers?

Struggling to achieve smooth scrolling across different browsers? Despite trying various methods, nothing seems to be effective. Here is my current body styling: body { color: #4A4A4A; background-color: #191E25; font-family: 'arial' ...

How to Reverse an Array in Java

I have populated an array with numbers from 1 to 10 using a for-loop. Now, I am trying to populate a second array with the values from the first array in reverse order, so the second array should contain numbers from 10 to 1. However, my current attempt i ...

Using Node JS to pass variables to the client

Currently, I am utilizing Node JS and Express for my server-side needs. In my server-side code, I pass a variable (sources) to my EJS template. Part of this variable is used to populate a list on the webpage. However, when a user clicks on an item in the ...

What is the process of managing memory in React components?

Seeking clarification on how memory storage works within the lifecycle of a React component. Does each component have its own designated memory allocation, and is this memory cleared whenever a component is unmounted? Any insights, whether brief or detail ...

Why isn't my output being shown on the screen?

Why is the output (refresh value) not being displayed? function myFunction() { $a = document.getElementById("examplehtml").value; document.write("<big><bold>"); document.write($a); document.write("</bold></big>"); $b = ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...

Node.js application encountering crashes while attempting to download a sizable file

I'm currently working on a project that involves converting HTTP URLs to torrents. The program is designed for downloading smaller files, typically between 1-500Mb. However, I've encountered an issue where the application crashes or times out whe ...

Customizing material-ui styles within a nested component

I am looking to modify the position of the expandIcon in an ExpansionPanel by changing the right attribute: <ExpansionPanel> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}&g ...

Is it possible to utilize jQuery for loading an external PHP file?

Apologies for the simplicity of my question, but I've been struggling to pinpoint the issue. I have a basic HTML form with just one checkbox. My goal is to use jQuery to load an external PHP file onto the same page within the 'content' div i ...