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

Steps to Verify if Cookie is Turned Off in a Next.js Application

I have encountered an issue with my Next.js App. It seems to be functioning properly until I disable cookies in the browser. Is there a way for me to determine if cookies are disabled in the browser and display a corresponding message? I attempted to check ...

Error: Unable to locate font in the VueJS build

Within my config/index.js file, I have the following setup: ... build: { index: path.resolve(__dirname, 'dist/client.html'), assetsRoot: path.resolve(__dirname, 'dist'), assetsSubDirectory: 'static', assetsPub ...

Data manipulation with Next.js

_APP.JS function MyApp({ Component, pageProps }) { let primary = 'darkMode_Primary'; let secondary = 'darkMode_Secondary' return ( <Layout primary_super={primary} secondary_super={secondary}> <Component {...page ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

Understanding the Vue lifecycle methods for updating Vuex state

Utilizing Vue and Vuex components, the code within my component consists of: computed: { ...mapState({ address: state => state.wallet.address }) }, The functionality operates smoothly in the user interface. However, my objective is to invoke a ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Error in TypeScript on SendGrid API: Invalid HttpMethod

Here is my code snippet: import sendgridClient from '@sendgrid/client' sendgridClient.setApiKey(process.env.SENDGRID_API_KEY); const sendgridRequest = { method: 'PUT', url: '/v3/marketing/contacts', bo ...

The process of rendering children elements in React

I have a question about managing children components in React. While there are resources available explaining this concept, I believe a more detailed explanation would be helpful. Let's consider the structure of my React component tree, which looks l ...

Tips for resolving the trigger problem with onChange in the PinInput Component of chakra-ui

The PinInput Component's onChange event is not functioning properly with the value in Chakra-UI. This issue causes the focus to automatically shift to the next input even when the value hasn't changed. For instance, when attempting to set the st ...

How can you retrieve a value in NodeJS Promise (Q) even when the promise fails?

As I dive into the world of promises in my NodeJS projects, I encountered a challenging situation. Despite reading the Promises/A+ spec and conducting extensive searches online, I struggled to find an elegant solution for accessing a value generated within ...

Incorporate several websites into a React application without using iframes

After developing a React application with create-react-app, I attempted to embed another website onto the app using an iframe. Everything worked perfectly until I wanted to resize the iframe to fit the page, resulting in a Blocked a frame with origin from ...

Which child node of the html tag represents the "text"?

In my quest for answers, I have searched extensively but to no avail: As we all know, when a web page is loaded in a browser, it generates a tree-like structure called the Document Object Model (DOM). This allows Javascript to manipulate the elements of t ...

Exploring the variations in method declarations within Vue.js

Today, while working with Vue, I came across an interesting observation. When initially using Vue, there were two common ways to define a method: methods: { foo: () => { //perform some action } } and methods: { foo() { / ...

I'm attempting to store the information from fs into a variable, but I'm consistently receiving undefined as the output

I'm currently attempting to save the data that is read by fs into a variable. However, the output I am receiving is undefined. const fs = require("fs"); var storage; fs.readFile("analogData.txt", "utf8", (err, data) =&g ...

Custom validation preventing Ng-minlength from functioning correctly

I'm currently working on an angularJS project where I am trying to create a form for users to input their username. The application needs to validate if the username is available in the database and if it falls within a character length of 5 to 10. & ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

Efficiently pinpointing the <div> element with precision using jQuery

I am building an interactive quiz for users of my app. The questions are table based, and can be answered "yes," "no," or "maybe." If the user answers "no" or "maybe," I would to slide open an informational panel that lives beneath the table. Here is the ...

Ways to find the image source using JavaScript/Jquery upon page loading?

I've scoured countless forums, yet a viable solution still eludes me. My objective is simple - upon page load, I want to gather all elements with the ".home" class and store them in an array called arr. Subsequently, the script should iterate through ...

Adjust the transparency of a separate image within a different container by hovering over another image container

Is my goal too complex to achieve? I am attempting to create a hover effect where the opacity of artwork1 and button1 changes simultaneously when hovered over. However, I am having trouble properly labeling my elements and getting them to interact as inten ...

Ways to deactivate a button with a designated identification through iteration using jQuery

Can't Figure out How to Deactivate a Button with Specific ID $('.likes-button').click(function(){ var el= this; var button1 = $(el).attr('id'); console.log(button1) $('#button1').attr("disabled",true); }) ...