Retrieve the most recent version based on the provided ID and date within the array

I am working with an array of JavaScript objects that have specific properties: _id, isVersionFrom, createdAt. The _id and isVersionFrom properties store MongoDB _ids (with isVersionFrom being false for the original object), while createdAt stores a timestamp from epoch. My goal is to extract an array containing only the latest version for each _id.

For example, consider the following array:


[
  {
    _id: 'CXsqvJ3ArwpM7aQwg',
    createdAt: 1493630867411,
    isVersionFrom: false
  },
  {
    _id: 'nnFthaqJ254BQozSp',
    createdAt: 1493630967411,
    isVersionFrom: 'CXsqvJ3ArwpM7aQwg'
  },
  {
    _id: 'Jksfe6Aaof9hT8CW9',
    createdAt: 1493631067411,
    isVersionFrom: 'CXsqvJ3ArwpM7aQwg'
  },
  {
    _id: 'HSitgQdFwYHqCjRax',
    createdAt: 1493631067411,
    isVersionFrom: false
  },
  {
    _id: 'vhZZCKhyQgkNSGjqK',
    createdAt: 1493631077411,
    isVersionFrom: 'HSitgQdFwYHqCjRax'
  },
]

The expected result should be:


[
  {
    _id: 'Jksfe6Aaof9hT8CW9',
    createdAt: 1493631067411,
    isVersionFrom: 'CXsqvJ3ArwpM7aQwg'
  },
  {
    _id: 'vhZZCKhyQgkNSGjqK',
    createdAt: 1493631077411,
    isVersionFrom: 'HSitgQdFwYHqCjRax'
  },
]

This entails filtering out all older versions of each ID.

Answer №1

UPDATED This example offers a potential solution utilizing Underscore:

const data = [
  {
    _id: "CXsqvJ3ArwpM7aQwg",
    createdAt: 1493630867411,
    isVersionFrom: false
  },
  {
    _id: "nnFthaqJ254BQozSp",
    createdAt: 1493630967411,
    isVersionFrom: "CXsqvJ3ArwpM7aQwg"
  },
  {
    _id: "Jksfe6Aaof9hT8CW9",
    createdAt: 1493631067411,
    isVersionFrom: "CXsqvJ3ArwpM7aQwg"
  },
  {
    _id: "HSitgQdFwYHqCjRax",
    createdAt: 1493631067411,
    isVersionFrom: false
  },
  {
    _id: "vhZZCKhyQgkNSGjqK",
    createdAt: 1493631077411,
    isVersionFrom: "HSitgQdFwYHqCjRax"
  }
];

// Utilize chain underscore methods for seamless processing.
const solution = _.chain(data)
  // Group items based on isVersionFrom or original _id.
  .groupBy(item => (!item.isVersionFrom ? item._id : item.isVersionFrom))
  // Find the latest item in each group by date.
  .map(val => _.max(val, item => item.createdAt))
  // Retrieve the final result.
  .value();

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

Leverage arrays within a personalized filtering system

I have created an array with the structure shown below... $scope.myArr = [arg1, arg2]; Now, I am interested in developing a custom filter that will accept this array as input and compare it to another array. For instance, I intend to use it in the follow ...

transmit FormData containing two files and a text message to the controller

I have encountered an issue while trying to send a FormData object containing text fields, an image file, and a PDF file to an action in the controller. Despite my efforts, the form data is not being sent to the action. I have checked for errors through br ...

Message from Discord: Unable to access the property 'MessageEmbed' because it is undefined

Attempting to create a simple welcome message embed. Here is my main.js file without the login token: const Discord = require('discord.js'); const client = new Discord.Client(); const MessageEmbed = new Discord.MessageEmbed(); const prefix = &ap ...

Ways to extract pertinent information from a PHP API

I've been attempting to add parameters to my query, but I keep getting inconsistent results. Despite trying different methods, I haven't been successful. Take a look at the code below. First, here is my code that functions properly without using ...

Error: The JSON data type is not recognized - Asp.Net MVC 4

I've been struggling to send a complex JSON object to my action with no success. Below is my javascript code: $.ajax({ url: "http://localhost:52593/" + urlAction.Controller + "/" + urlAction.Action, type: type, dataType: dataType, da ...

ForEach function does not work following a shallow copy

I'm encountering an issue where forEach is not recognized as a function. Can someone assist me with this problem? Essentially, I need to generate a shallow copy of filteredSettlements and use it for looping through the items. Below is a snippet of the ...

The map function is mistakenly returning double the amount of the object it should be returning

My program is fetching data from an API, but when I try to map the array for interesting data, it downloads the same object multiple times. For the first search, it downloads the object twice and for subsequent searches, it downloads the object six times. ...

"Transferring a JSONArray from an Activity to an HTML Script: A Step-by

Is there a way to transfer a JSONArray from an Activity to an HTML Script? I have attempted the method below but I am not receiving the data in the HTML Activity:- public class DayViewJSActivity extends Activity { WebView webviewobj; String jsu ...

Steps to activate a particular Bootstrap tab upon clicking a hyperlink

Trying to implement a Bootstrap tab panel in the following manner: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href ...

Is there a method to iterate through dynamically added nested arrays, similar to the Russian Matryoshka dolls?

I am facing a challenge in my Angular TypeScript class where I need to define a function that can loop through dynamically added nested arrays. The issue arises because my template displays a custom Kendo grid which requires me to traverse a type of "Matri ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

To enable communication between methods, you can easily add a property to a JavaScript class component

Is there a better way to communicate between methods in a class? class T extends React.Component { constructor(props) { super(props) this.a = false; } methodA { //will set 'a' in this method, maybe async. } ...

Trigger an event upon completion of the angular $route.reload() function

I am encountering an issue where I need to refresh the route using the following code: $route.reload(); However, I also need to trigger a function just before the template is rendered again. For instance: $("#someTab").click(); Your help would be grea ...

Is there a way to calculate the number of days between two selected dates using the bootstrap date range picker?

I recently implemented the bootstrap daterange picker for selecting start and end dates, and it's been working perfectly. However, I now have a requirement to display the count of days selected. Here's my current code: $('input[name="datera ...

How to transmit data using ajax through a hyperlink? (Without relying on ExtJS, jQuery, or any other similar libraries)

I have a link that says "follow me" and I want to send some basic data to the page without having it reload. Update: I just realized that using "onclick" will help me achieve what I need. Got it. Update 2: I mean, something like this: follow me ...

The error message indicates that the argument cannot be assigned to the parameter type 'AxiosRequestConfig'

I am working on a React app using Typescript, where I fetch a list of items from MongoDB. I want to implement the functionality to delete items from this list. The list is displayed in the app and each item has a corresponding delete button. However, when ...

Obtaining Data from Fetch Response Instance

Currently, I am utilizing the fetch method to execute API requests. While everything is functioning as expected, I have encountered a challenge with one specific API call due to the fact that it returns a string instead of an object. Normally, the API pro ...

What is the best way to monitor live updates in a MongoDB database?

How can I implement real-time updates using a MongoDB database in Node.js? I'm currently using Mongoose with Express. I found an example code snippet in the MongoDB Change Streams documentation at https://docs.mongodb.com/manual/changeStreams/ const ...

Mandate distinct fields when storing embedded records

device.rb class Device include Mongoid::Document field :devui, type: String field :name, type: String belongs_to :user embeds_many :responses When fetching data from an external server, a JSON with an id field is obtained. When trying to insert ...

Click on a button to display the corresponding DIV while hiding the rest, all achieved with the power of Vue

I'm seeking guidance as a newcomer to Vue, so please bear with me if my question appears simplistic. My scenario involves a set of buttons and corresponding div elements. The goal is to show a specific div when its associated button is clicked, while ...