Removing a specific date value within an object contained in an array, then organizing the array in descending order based on the latest date

I need help sorting an array of objects by the most recent created_at value while maintaining the entire object in that order. Currently, my code only returns the create_at value instead.

How can I adjust the map function to avoid separating the created_at value from the rest of the object?

var notes = [
    {
        country: "Angola",
        denomination: 50,
        currency: "Kwanzas",
        issue_date: 2012,
        created_at: "2017-07-20T18:41:15.000Z",
        updated_at: "2019-07-20T18:41:15.000Z"
    },
    ...
]

var dateMap = notes.map(note => note.created_at.substring(0,10)).sort().reverse()

The desired result should look like this:

dateMap = [
    {
        country: "Angola",
        denomination: 50,
        currency: "Kwanzas",
        issue_date: 2012,
        created_at: "2017-07-20T18:41:15.000Z",
        updated_at: "2019-07-20T18:41:15.000Z"
    },
    ...
]

Answer №1

Customize your comparator:

const sortByYear = item => item.date_published.substring(0, 4);

items.sort((x, y) => sortByYear(y).localeCompare(sortByYear(x)));

Answer №2

To achieve the sorting you need, compare the property values within the sort function:

notes.sort((a, b) => b.created_at.localeCompare(a.created_at))

console.log(notes)
<script>
  var notes = [{
      country: "Angola",
      denomination: 50,
      currency: "Kwanzas",
      issue_date: 2012,
      created_at: "2017-07-20T18:41:15.000Z",
      updated_at: "2019-07-20T18:41:15.000Z"
    },
    {
      country: "Rwanda",
      denomination: 5000,
      currency: "Francs",
      issue_date: 2009,
      created_at: "2008-07-20T18:41:15.000Z",
      updated_at: "2019-07-20T18:41:15.000Z"
    }, 
    // Additional data entries
  ]
</script>

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

Transform the Nodejs server into a reusable Node module

Can a nodejs API server be transformed into a node module for use in other projects with minimal code modifications? Additional Information: The node js server contains various APIs (get, post, put). If I integrate this server as a node module within anot ...

Transmitting arrays containing alphanumeric indexed names via ajax requests

I am facing a challenge in passing an array through a jQuery Ajax call. My requirement is to assign descriptive indexes to the array elements, for example, item["sku"] = 'abc'. When I create the following array: item[1] = "abc"; ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

What is the best way to stop this Jquery slider from moving?

I've been struggling with this issue for what feels like forever, and it's driving me crazy! I have a slider on the homepage that I'm trying to enhance with a "click to pause" feature (and maybe even a click to resume, for good measure). I ...

The error occurred in Commands.ts for Cypress, stating that the argument '"login"' cannot be assigned to the parameter of type 'keyof Chainable<any>))`

Attempting to simplify repetitive actions by utilizing commands.ts, such as requesting email and password. However, upon trying to implement this, I encounter an error for the login (Argument of type '"login"' is not assignable to parameter of t ...

What causes delays in the calculation of element heights and widths by jQuery's height() and width() methods?

Recently, I've encountered a performance issue with jQuery's height() and width() methods taking too long to calculate an element's height and width. How can I optimize these methods for Internet Explorer 8+, as well as the latest versions o ...

What is the most efficient way to temporarily transform a button into a tab switcher?

Review this snippet of code within a jQuery event listener. The element $(this) refers to a <form>. const submitButton = $(this).find('[type=submit]'); submitButton.removeClass('btn-primary') ...

How can I convert hexadecimal to a string using C?

Hello, I am currently using digi dynamic c and I am attempting to convert the following data into a string: char readingreg[4]; readingreg[0] = 4a; readingreg[1] = aa; readingreg[2] = aa; readingreg[3] = a0; At this moment, my printf statements require f ...

Currently experiencing difficulty with arrow key navigation in ReactJS

I'm attempting to create a xmb (psp/ps3) menu using react, but I've encountered an issue. The problem is that the items scroll past each other instead of moving in order. For example: Item 1 jumps to Item 3 (skipping Item 2, even though it should ...

The div element disappears upon calling the load() function

Currently, I am working to implement sorting criteria (such as by price or author) on my jsp page. I am utilizing ajax to refresh the content of a div when a new sorting option is selected. However, upon calling the reload function, the div just disappears ...

What could be causing my insertRow function to inject empty cells into my table?

I am facing an issue with adding the results of a fetch request into a table as a new row. Strangely, when I click the button to trigger this function for the first time, it adds an empty row instead of the desired data. However, on subsequent clicks, the ...

When integrating React with Tawk, the user's name and email are automatically encoded before being sent

My code within the componentDidMount() function initializes a widget popup when the page loads. It then sets the name and email using parameters received from the previous page. const fullName = this.state.data[0]; console.log(fullName); const e ...

When the onChange event is triggered, the current value in my text input field disappears in React

Just starting out with Reactjs and I'm working on creating a page where users can edit their own posts. Currently, when I try to modify the existing text in the text input, the form gets cleared and the user has to re-enter the data. This is not the b ...

Ways to handle Sessions in Node.js

I'm attempting to utilize a website within node.js. However, the site is prompting me to enable the storage of session cookies. I attempted to set up a cookie-jar, but I couldn't get it to work. Here is a simplified version of the code that is c ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

Can we connect to an external PHP script using Ajax?

I'm attempting to utilize Ajax to call an external PHP script in the following manner: $(function() { $.ajax({'url': 'http://stokes.chop.edu/web/zscore/result.php', 'type': 'POST', & ...

Ways to verify if a string contains a specific template literal in javascript

I attempted to verify this by using the str.includes('${') method as a straightforward approach, but it did not produce the expected results. I found that it also returned strings that didn't contain the specified characters. For instance, ...

There was an issue when trying to process the Javascript data structure with JSON.parse

Currently, I have the following data stored in a JavaScript variable: "{'Headings': [{'name': 'Behavior', 'majorTopic': 'N', 'vote': {'down': 1, 'up': 1}}, {'na ...

What is the best method for interpreting XML using JavaScript?

I am facing a challenge with fetching and parsing an XML file using JavaScript. The XML-file is beyond my control. Recently, there has been a change in the encoding of some XML files which prevents the code from being parsed successfully. Previously it wa ...

"Delightful Data Display: Achieving Ajax Triumph with

When I include the success function in my DataTable, the rows do not automatically fill up in the table. However, when I remove the success function everything works correctly, and the datatable fills with data as expected. I am trying to retrieve a messag ...