Arranging an array of objects in Javascript based on the first attribute, and in cases of equality, sorting with another attribute

I have an array structured like this:

let myarr = 
[{id:1 , name: "mark" , birthday: "1990-08-18"},
{id:2 , name: "fred" , birthday: "1990-08-17"},
{id:3 , name: "franck" , birthday: "1990-08-16"},
{id:4 , name: "mike" , birthday: "1990-08-15"},
{id:5 , name: "jean" , birthday: "1990-08-17"}]

I am currently sorting these objects by their "birthday"

myarr.sort((a, b) => new Date(b.birthday).getTime() - new Date(a.birthday).getTime());

However, there are instances where two objects have the same birthday value. In these cases, I would like the sort function to prioritize the object with the higher "id".

Any suggestions on how to achieve this?

Answer №1

To improve the sorting functionality, it is recommended to include an additional case within the sort function like so:

let peopleArray = [
{id:1 , name: "Alice" , birthday: "1990-08-18"},
{id:2 , name: "Bob" , birthday: "1990-08-17"},
{id:3 , name: "Charlie" , birthday: "1990-08-16"},
{id:4 , name: "David" , birthday: "1990-08-15"},
{id:5 , name: "Eve" , birthday: "1990-08-17"}
]

peopleArray.sort((a, b) => {
     let difference = new Date(b.birthday).getTime() - new Date(a.birthday).getTime();
     if(difference != 0) return difference;
     else return b.id - a.id;
});
console.log(peopleArray);

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

Learning how to integrate Next.js, React.js, and Redux into an HTML page for an enhanced user

My current project is built on Asp.Net MVC, but the technology used is not crucial. I integrated react.js and redux for searching a section of my html page using a cdn link. Now, I am considering deploying the server side of the application with next.js. ...

Your search parameter is not formatted correctly

I am currently working on filtering a collection based on different fields such as name by extracting the values from the URL parameters. For example: http://localhost:3000/patient?filter=name:jack I have implemented a method to retrieve and convert these ...

Unlocking bundles of worth through javascript coding

Is there a way to retrieve a set of values using javascript? Upon page load, I am looking to display an alert showing the value '0-1' for any checked checkboxes. View example here var checkBoxes = document.getElementsByName('mailId[]&apos ...

Substituting placeholders within a docx template remains incomplete

Utilizing this specific library, I am implementing a feature to substitute placeholders within a docx template and generate multiple documents. The technologies involved are neutralino and vue for the front-end, where I have devised a method that transmits ...

Discover how to use Jest and Enzyme to test for any string as the defaultValue on an input field

As a beginner in the world of testing, I've been exploring the airbnb / jest documentation to troubleshoot an issue with a test. So far, I haven't been able to come up with a solution that actually works. The snapshot contains a defaultValue tha ...

Passing an array from PHP to JavaScript using AJAX

Here is the code snippet on the server side: <?php header('Content-Type: text/html; charset=utf-8'); require "../general.variables.php"; require "../functions_validation.php"; require "../functions_general.php"; require "../../db_con.php"; $ ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

Converting SHA1 function from JavaScript to Python

Can you help with translating this Javascript code to Python? def sha1(str1, raw): hexcase = 0 chrsz = 8 str1 = utf16to8(str1) def utf16to8(str): out = "" len = len(str) i = 0 while i < len: ...

Is it possible to measure the CPU utilization in a TypeScript application programmatically?

Is there a method to calculate CPU usage as a percentage and record it in a file every 20 milliseconds? I'm interested in exploring different approaches for accomplishing this task. Your insights would be greatly appreciated! I've come across so ...

Updating a query parameter with jQuery

Looking for a way to modify the value of a query parameter in a URL using jQuery. There are two example URLs: www.domain.com/?id=10&name=xxx and www.domain.com/?name=xxx&id=10 I want to update the id parameter to something like www.domain.com/ ...

Issue experienced with Vue2 where utilizing a computed property to filter a nested v-for structure

I have a unique HTML challenge that requires me to iterate through an unconventional data setup. The information is retrieved in two separate parts from Firebase: one for categories and another for businesses. The structure of the data is as follows: Busi ...

Why is it important to have specific property names?

Here is some code and HTML for triggering a radio button. It seems to work fine without any issues, but I'm wondering if the presence of a name property is necessary. When I remove the name property, it stops working. Can someone explain why? <inp ...

Display alert only when focus is lost (on blur) and a dropdown selection was not made

Utilizing Google Maps Places for autocompletion of my input, I am aiming to nudge the user towards selecting an address from the provided dropdowns in order to work with the chosen place. A challenge arises when considering enabling users to input address ...

Dynamically add a plugin to jQuery during execution

After installing jQuery and a jQuery-Plugin via npm, I am facing the challenge of using it within an ES6 module. The issue arises from the fact that the plugin documentation only provides instructions for a global installation through the script tag, which ...

Connecting a text input in a nested component to the data passed down from its parent component in VueJS

My VueJS setup involves a child component sending data to a parent component, which then tries to route the data to a sibling of the child to create new components. I'm using a dictionary to group the data and push it into an array. The array is then ...

What is the best way to solve the problem of Chrome auto-complete overlapping with labels in Vuetify?

When attempting to make a login form using outlined text fields in Vutify, there is an issue with Chrome autocomplete overlapping the labels. <v-text-field v-model="email" label="e-mail" name="email" outlined prep ...

Logging DOM elements with Electron's webview preload feature

Within my Electron program, I am utilizing a webview in my index.html file. The webview is equipped with a preloader, and my goal is to manipulate the DOM of the webview specifically, not just the index.html file. In my preloader code snippet below, the c ...

Utilizing event bubbling in Angular: a comprehensive guide

When using Jquery, a single event listener was added to the <ul> element in order to listen for events on the current li by utilizing event bubbling. <ul> <li>a</li> <li>b</li> <li>c</li> <li>d< ...

Supabase Authentication User Interface Error: Uncaught TypeError - Unable to access properties of null (specifically 'useState')

Concern Whenever I incorporate this Auth component into my login page, I encounter an issue. I am attempting to adhere to the guidelines provided in Supabase Auth with Next.js Pages Directory. If you suspect that this problem stems from a version discrepa ...

Unable to retrieve file from server

Apologies for the basic question, but I'm feeling a bit lost at the moment. I've been diving into learning JavaScript and decided to set up a page on the 00webhost site to experiment and run tests. Everything was going well until I hit a roadblo ...