Guide on extracting unique identifiers from an array of objects and sorting them by the earliest date in JavaScript

I've got an array of objects and I'm looking to retrieve the items with unique IDs while also selecting the earliest date.

For example: [{id:1, date: Jan 12}, {id:2, date: Feb 8}, {id:3, date: Feb 8}]

var array = [{id: 1, date: Jan 12 2021 08:00:00 AM}, {id: 2, date: Feb 8 2021 08:00:00 AM}, {id: 2, date: Mar 2 2021 08:00:00 AM}, {id: 3, date: Feb 8 2021 08:00:00 AM}]

Edit: I forgot to mention that the date format is a string formatted as moment("MM-DD-YYYY");

This is what I have so far:

var withId = array.filter(function (g) { return g.Id != null });

withId = array.filter(function (e) { return moment(e.UtcStart) < moment() && e.DteEndDate != null ? moment(e.DteEndDate) > moment() : true });

withId.sort(function (a, b) { return moment(a.UtcStart) - moment(b.UtcStart) });

var key = 'Id';

var unique = [...new Map(withId.map(x => [x[key], x])).values()];

Answer №1

To achieve the desired outcome, you can utilize the Array.reduce() method. By iterating through each item in the array, we create a map based on the unique identifier id. If the date of the current item is earlier than the existing entry in the map at acc[id], we replace it:

var data = [{id: 1, date: 'Jan 12 2021 08:00:00 AM'}, {id: 2, date: 'Feb 8 2021 08:00:00 AM'}, {id: 2, date: 'Mar 2 2021 08:00:00 AM'}, {id: 3, date: 'Feb 8 2021 08:00:00 AM'}];

const result = Object.values(data.reduce((acc, { id, date }) => { 
    if (!acc[id] || Date.parse(acc[id].date) > Date.parse(date)) acc[id] = { id, date };
    return acc;
}, {}));

console.log('Final Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To order your array according to dates is essential.

let array = [{id: 1, date: 'Jan 12 2021 08:00:00 AM'}, {id: 2, date: 'Feb 8 2021 08:00:00 AM'}, {id: 2, date: 'Mar 2 2021 08:00:00 AM'}, {id: 3, date: 'Feb 8 2021 08:00:00 AM'}]
let sortedArray = array.sort((a, b) => new Date(b.date) - new Date(a.date))// reverse sorting for Map to retain last value of same key
let twoDeimentionalArray = sortedArray.map(item=>[item.id,item.date])
let map = new Map(twoDeimentionalArray)//Create a set

and focus on it.

Moreover

var array = [
{id: 1, date: 'Jan 12 2021 08:00:00 AM'}, 
{id: 2, date: 'Feb 8 2021 08:00:00 AM'}, 
{id: 2, date: 'Mar 2 2020 08:00:00 AM'}, 
{id: 3, date: 'Feb 8 2021 08:00:00 AM'},
{id: 2, date: 'July 8 2022 08:00:00 AM'},
{id: 4, date: 'Feb 8 2021 08:00:00 AM'}
]
let sortedArray = array.sort((a, b) => (new Date(a.date) - new Date(b.date))).sort((a, b) => (a.id- b.id))

const reducedArray = sortedArray.reduce(function(set,item){
    return (set.length !== 0 && set[set.length-1].id == item.id) ?  set : set.concat(item)
},new Array)
console.log(sortedArray)
console.log(reducedArray)

Answer №3

Is eliminating the later date with the same ID a viable solution?

var array = [{id: 1, date: "Jan 12 2021 08:00:00 AM"}, {id: 2, date: "Feb 8 2021 08:00:00 AM"}, {id: 2, date: "Mar 2 2021 08:00:00 AM"}, {id: 3, date: "Feb 8 2021 08:00:00 AM"}]
var uniqMap = {};
array.forEach(v => {
    if (!uniqMap[v.id] || (Date.parse(v.date) < Date.parse(uniqMap[v.id]))) {
        uniqMap[v.id] = v;
    }
})
console.log(uniqMap);
// convert map to array
var uniqIds = Object.keys(uniqMap).map((key) => uniqMap[key]);
console.log(uniqMap);

// output displayed:
0: {id: 1, date: 'Jan 12 2021 08:00:00 AM'}
1: {id: 2, date: 'Feb 8 2021 08:00:00 AM'}
2: {id: 3, date: 'Feb 8 2021 08:00:00 AM'}

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

Is it possible to utilize ajax for submitting a form only after it has been validated by the

Currently, I am utilizing a jQuery plugin for validation and incorporating AJAX for form submission. My objective is to submit the form only after successful validation; however, the issue arises where the form gets submitted regardless of the validation o ...

Oops! It appears that there is an error saying "Data.filter is not a function"

I've encountered an issue where I pass a prop from parent to child and then return it, resulting in a 'filter is not a function' error. Any assistance in identifying the cause of this error would be greatly appreciated. Here is the array th ...

Re-calculating with Jquery when input is updated

I am looking for guidance on how to make the calculator recalculate based on a change in the #calcTotal input field. I have successfully calculated all fields and managed to update the #cwac field when one of the values before it changes. Here is the HTML ...

Switching Image Values in JavaScript: A Quick Guide

After successfully using a JavaScript function to swap the src of two images, I encountered an issue. I also needed to switch two values associated with the images so that I could calculate them later. For example: img src="ble.jpg" id="F" value="" onclic ...

Exploring the mern.io scaffolder tool - Unraveling the essence of the .need method

While exploring the code of the scaffolder mern.io, I came across an intriguing method called ".need". It appeared to be related to es6 classes, but unfortunately, I couldn't find any valuable information about it. Thus, I'm curious to know: what ...

Discovering and updating a DOM element with a rejuvenating touch: Angular JS

Although not very experienced with Angular JS, here's what I currently have and what I aim to achieve: <div ng-app="MyApp" ng-controller="appController"> <div class="input-group"> <input class="form-control enableEnter" type=" ...

Jade iterates over each object element, assigning its children to their respective parent elements

I have a JavaScript Object named "boards". [{"id":1,"parent_board":0,"title":"Lorem 1","description":"ec40db959345153a9912"}, {"id":2,"parent_board":0,"title":"Lorem 2","description":"bb698136a211ebb1dfedb"}, {"id":3,"parent_board":1,"title":"Lorem 1-1"," ...

What is the best way to differentiate between two calls to the same method that are based on different arguments?

Currently, I am utilizing sinon to mock functions from Google Drive in my NodeJS project. In a single test scenario, I make two separate calls to the create method (without the ability to restore between calls): // Call 1: drive.files.create({ 'reques ...

Anticipating the completion of post requests

I am currently working on implementing a file upload feature in Angular. I have tackled the issue of file size restrictions by creating an API endpoint that can receive file chunks. Once all the chunks are received, another endpoint needs to be triggered ...

The session feature in Express is malfunctioning

Incorporating express-session into my app, I attempted the following proof of concept (POC):. server.js app.use(session({ secret: 'pal!lap789', // create new redis store. store: new redisStore({ host: 'localhost ...

Did the IBM MobileFirst client miss the call to handleFailure?

I am currently utilizing the IBM MFP Web SDK along with the provided code snippet to send challenges and manage responses from the IBM MobileFirst server. Everything functions properly when the server is up and running. However, I have encountered an iss ...

The addition operation in JavaScript seems to be malfunctioning as it is not adding up my values

After encountering an issue with calculating the number of payments, I discovered that the addition operator was not functioning as expected. Instead of summing up values, it was treating them as strings. For instance, when trying to add 3 and 5, the out ...

What are the steps for utilizing ckeditor to send textarea information via ajax?

Here is the code snippet that controls the textarea in my chat application: <div class="chat"> <div class="messages"></div> <textarea class="entry" name="entry" placeholder="Welcome to the Chat. Enter your message here!">&l ...

In JavaScript, the task involves filtering through multiple arrays of objects to calculate the average value based on the contract number

Every object in the Array contains a contractNumber, but with repeated values. I am attempting to determine the average value of each unique contractNumber. var vendorArr=[{ "contractNumber":5258, "monthId":0, "value":2}, { ...

Converting a string to regular text in JavaScript (specifically in ReactJS)

When I fetch data from an API, sometimes there are special characters involved. For example, the object returned may look like this: { question : "In which year did the British television series &quot;The Bill&quot; end?" } If I save t ...

Managing Asynchronous Callbacks in JavaScript using Node.js

I am a beginner in the world of Javascript and I recently encountered a challenge with async callbacks using Node.js. My first step was setting up the Facebook webhook and sending a Webhook POST request Below is the code snippet : routes.js **Setting up ...

Tips for preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

Creating a unique function to map an array in VueJS specifically designed for table manipulation

I am currently working on displaying and sorting data in a bootstrap table within VueJS. My goal is to change the date format within an array retrieved from an API endpoint. The original date format is in "January 21, 2010" and I need it to be in "MM/DD/Y ...

Seems like the ng-show events inside are not being triggered, almost like an invisible image

I am encountering an issue where no JavaScript events are triggering inside an ng-show div in my code. You can access my code through the following link on Plnkr: http://plnkr.co/edit/kGqk8x?p=preview Upon loading data from JSON, I set ng-show to true. Ho ...

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...