Order the object by the maximum date

Looking to organize the object based on the maximum date for each ID. Certain IDs may have multiple dates associated with them. The example below showcases an object where id:123 has two different dates. In this case, we aim to identify the highest date for user 123. I have attempted to achieve this by using the sort method and storing the first element of the array, but it seems like there is a missing piece in the puzzle.

var arr = [
  {
    "scores": [
      {
        "score": 10,
        "date": "2021-06-05T00:00:00"
      }
    ],
    "id": "3212"
  },
  {
    "scores": [
      {
        "score": 10,
        "date": "2021-06-05T00:00:00"
      },
      {
        "score": 20,
        "date": "2021-05-05T00:00:00"
      }
    ],
    "id": "123"

  },
  {
    "scores": [
      {
        "score": 5,
        "date": "2021-05-05T00:00:00"
      }
    ],
    "id": "321"
  }
]

This is what I've attempted:

 _.each(arr, function (users) {
                users.scores = users.scores.filter(scores => new Date(Math.max.apply(null, scores.date)));
                return users;
            });

The desired output should display as follows, showcasing the maximum date selected for each ID:

[
  {
    "scores": [
      {
        "score": 10,
        "date": "2021-06-05T00:00:00"
      }
    ],
    "id": "3212"
  },
  {
    "scores": [
      {
        "score": 10,
        "date": "2021-06-05T00:00:00"
      }
    ],
    "id": "123"

  },
  {
    "scores": [
      {
        "score": 5,
        "date": "2021-05-05T00:00:00"
      }
    ],
    "id": "321"
  }
]

Answer №1

Your filter callback function needs to be adjusted in order to correctly filter the desired element. It is recommended to convert date strings into date objects for consistent and accurate results, regardless of the format.

One solution involves using a combination of Array.map() and Array.sort() to process and organize your data effectively.

const data = [{
    'scores': [{
        'score': 10,
        'date': '2021-06-05T00:00:00'
    }],
    'id': '3212'
}, {
    'scores': [{
        'score': 10,
        'date': '2021-06-05T00:00:00'
    }, {
        'score': 20,
        'date': '2021-05-05T00:00:00'
    }],
    'id': '123'
}, {
    'scores': [{
        'score': 5,
        'date': '2021-05-05T00:00:00'
    }],
    'id': '321'
}];

// Map the data and update the objects with sorted scores
const result = data.map((user) => {
    const sortedScores = user.scores.slice(); // Copy original scores array
    sortedScores.sort((a, b) => (new Date(b.date) - new Date(a.date))); // Sort scores by date descending
    return {
        ...user,
        scores: [sortedScores[0]] // Return user with highest score
    };
});

console.log(result);

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

"Troubleshooting the issue of Delete Requests failing to persist in Node.js

Whenever I send a delete request to my node.js server, it can only delete one item from my JSON file until the server restarts. If I attempt to make a second delete request, it successfully deletes the item but also reverts the deletion of the last item. ...

unable to retrieve getters within the store module

This is the explanation of my store module. // rest defined earlier const _GETTERS = { getName: state => { return state.current.name; }, getLastName: state => { return state.current.lastName; }, getFullName: (state, getters) => ...

Vue. Where should this snippet be placed?

After delving into Vue, we were inspired by the concept of a store, which allowed us to separate page state from presentation. We developed an alert component that showcased the content of the alert string stored in store.pageError. As we aimed to incorpo ...

Issues encountered when updating values in MaterialUI's TextField using Formik

Within my React functional component, I utilize Formik for form management and MaterialUI V5.10 for styling. The form includes TextField elements and a Canvas element. I am encountering two issues... Despite setting initial values in Formik, the TextFiel ...

Updating the MLM binary tree system

In my JavaScript nested object, the IDs of objects increase in depth. By using JavaScript support, I added an object inside ID - 2 with a children array of 3. What I need is to update (increment) the IDs of all siblings in the tree. This code snippet shoul ...

Why does TypeScript not generate an error if props are not passed to a functional component?

How does TypeScript handle not passing down props to a functional component without throwing an error? Consider the following code snippet: interface Props{ id: string; className?: string; } export const Buttons: React.FC<Props> = () => { r ...

Executing a function in C# using JavaScript

Currently, I am utilizing selenium's RemoteWebDriver along with c#. At the moment, I am inserting a javascript function into the head of a page that has the following structure: "window.__webdriver_javascript_errors = []; window.onerr ...

What is the best way to send parameters to the Nuxt $fetch method?

Trying out the new fetch() method in my Nuxt project Struggling with implementing an infinitely scrolling list using fetch() Remembering that Nuxt triggers fetch on initial page load Finding myself manually calling fetch when loading mor ...

The XMLHttpRequest's readystate gets stuck at 1 stage

Feeling a bit out of practice here - used to work with AJAX directly, but then spent a few years on a jQuery site and now my native JS skills are rusty. I've simplified my code as much as possible, but it's still not functioning: var rawfile = ...

Switch Object to WebElement or SearchContext in JavaScript

Looking for the best way to convert an Object to WebElement or SearchContext using JavaScript? In Java, casting as `(WebElement)` or `(SearchContext)` works fine. However, attempting the same in JavaScript with `as Webelement` or `as SearchContext` result ...

Tips for disabling the default behavior by using preventDefault in JavaScript

I need help with removing the preventDefault() function and submitting the form in the else condition of my code. Does anyone know how to achieve this? if(email.val() != ""){ //check email e.preventDefault(); $.ajax({ ...

Determining the overall cost by factoring in the quantity for a recent purchase

Exploring the world of vue js for the first time has been quite exciting. I recently received a multidimensional array from the server side and my task is to render this array into HTML format. The array contains data about meals, including their title, si ...

What steps should I take to ensure my bootstrap form is fully responsive?

I'm struggling to make my form responsive. It looks fine on desktop, but not on mobile. As a beginner, I feel lost... Any help with this would be greatly appreciated. Here's the code snippet: <div class="container"> <div class="row ...

What is the best way to eliminate items from an array in a side-scrolling video game?

In my gaming project, I am creating a unique experience where the player needs to collect all the words from a given array. Currently, I am utilizing the shift() method to eliminate elements, as demonstrated in the code snippet below: if ( bX + bird.width ...

A function that receives another function as a parameter

I need assistance in defining a function that can call another function passed as a parameter within the main function. function displayMessage(title, message, button, callback) { console.log(title, message, button); if (typeof(callback) !== "f ...

Locate every JavaScript array available

I am in the process of converting a variable number of vector shapes into coordinates. Each shape's coordinates are stored within its own JavaScript array. For instance, the JavaScript code might be structured like this: var la0001 = [33,108,66,141, ...

The quirks of JSON.stringify's behavior

I am in the process of gathering values to send back to an ASP.NET MVC controller action. Despite using JSON.stringify, I keep encountering Invalid JSON primitive exceptions and I am unsure why. I have a search value container named searchValues. When I i ...

Please eliminate the forward slash (/) from the end of my route

Could anyone help me figure out how to remove the trailing slash at the end of routes in Nuxtjs? I attempted using the @nuxtjs redirect-module and setting the trailingSlash property to false, but instead of removing the slash, it adds multiple slashes at ...

What are the steps to implement PostgreSQL mod for Vert.x in JavaScript?

Hi there, I'm a newcomer to Vert.x and I am interested in utilizing the https://github.com/vert-x/mod-mysql-postgresql for a particular service. Below is a snippet of code that I am using for my web server: var vertx = require('vertx'); var ...

The AJAX request is failing to retrieve the JSON-encoded object

I am attempting to retrieve a JSON encoded object from a PHP file using jQuery and AJAX GET, but I seem to be encountering some issues. Below is the JavaScript code for my request: function fetchData() { $.ajax({ url:'ajax/dataFetch.php&a ...