Retrieve a collection of duplicate objects and choose the one with the most recent date

Having trouble figuring out how to solve a problem with manipulating an Object Array called items. The array contains four items in total.

  const items: any[] = await sp.web.lists.getByTitle("List")
          .items.select("ID, Part, Level, MyDate")
          .filter("Part eq 1")
          .getAll();

The issue I'm facing is how to manipulate the Array to achieve the following:

  1. Identify and remove duplicates for Level, leaving only one of each value;
  2. From the remaining unique values, eliminate the item with the oldest Date.

Unfortunately, I haven't been able to find a solution through my own research yet. Any help from the community would be greatly appreciated!

Answer №1

In searching for a resolution to my issue, I often find that a heavy workload can hinder progress.

//Identify and eliminate duplicates based on specific criteria
workItems = items

const lookup: any[] = workItems.reduce((a, e) => {
  a[e.Level] = ++a[e.Level] || 0;
  return a;
}, {});


const levels = workItems.filter(e => lookup[e.Level]);
//Determine the most recent date among duplicates and remove older instances
let isLast = levels[0];
for (let date of levels) {
  if (moment(date.YourDateField) > moment(isLast.YourDateField)) {
    isLast = date;
  }
}

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

What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = [ { "amount": 270, "xlabel": "25-31/10", "datestatus": "past", "color": "#E74C3C", "y": 270, "date": "2020-10-31T00:00:00Z", "entityId": 1, "entityName": "Lenovo HK", "bankName": "BNP Paribas Bank", "b ...

What impact does setting 'pathmatch: full' in Angular have on the application?

When the 'pathmatch' is set to 'full' and I try to delete it, the app no longer loads or runs properly. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { H ...

The Angulartics2GoogleAnalytics type does not have the property 'startTracking' in its definition

I have carefully followed the instructions provided in the readme file of https://github.com/angulartics/angulartics2, but I encountered the following error: ERROR in src/app/app.component.ts(21,33): error TS2339: Property 'startTracking' does n ...

I'm trying to figure out the best way to successfully pass a prop to another component in TypeScript without running into the frustrating issue of not being able to

I have been facing an issue while trying to pass a prop from a custom object I have defined. The structure of the object is as follows: export type CustomObjectType = { data?: DataObject }; export type DataObject = { id: number; name: stri ...

Tips for adding new data to an array in a JSON file without overwriting the existing contents

Is it possible to use the fs module to append an array to a JSON file without using databases? Will JSON suffice for this task, or should I explore alternative methods for data handling? Things I have attempted: let homeFile_JsData = { id: id, title: titl ...

Unable to retrieve React state within the callback function

As I work with the following components: const ParentComponent: React.FC = () => { // Setting newType to some value within the code const [newType, setNewType] = useState<any>(undefined); // Enabling addEdge to true in another part o ...

CodeIgniter throwing an error with converting Array to String?

Here is the code snippet: Controller File public function view_resume($id) { $this->load->model('ORB_Model'); $data['get_masterData'] = $this->ORB_Model->get_masterData($id); } Model File: public function get_ed ...

Custom number of arrays specified by the user

Currently working on coding: Main Class public class Ticket { // Method : Display the details of a ticket and list of Lucky Dip numbers on screen. public void displayTicket() { numbersClass.populateArray(); System.out ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Sequencing animations with *ngIf in Angular 6

In my component, there are two elements that utilize the same fade animation. Only one element is visible on screen at a time, controlled by *ngIf directives for visibility management. The animation is a simple fade in/fade out effect. When the state of m ...

Speedy method for declaring array elements incrementally - Java

Assume I have 10 integer variables, named x1 to x10. Defined below is an integer array: Int[] countup = new Int[10]; I wish to assign values to the array elements in the following manner: countup[0] = x1; countup[1] = x1 + x2; countup[2] = x1 + x2 + x3 ...

How can I hide a mat card in Angular when the array is empty?

Below is the code snippet from my Angular HTML file: <mat-card *ngFor="let getCartDetail of getCartDetails" style="margin-bottom: 1em; " > <div class="card-container"> <mat-card-ti ...

Enter the Angular Date Picker on Safari

While working with Angular and ngx-bootstrap, I encountered an issue where the input type=date does not function properly on Safari Browser. Can anyone suggest a solution to fix this problem? ...

Arranging numerous items based on date in JavaScript without prior knowledge

I'm facing an issue where I need to showcase JSON data containing events but want them sorted by time. The challenge is that the number of objects in the JSON can vary as users can keep adding more. Below is my code snippet demonstrating how the displ ...

When setting properties on the Object or Array prototype in JavaScript, it disrupts the functionality of brackets

Similar Question: Adding functions to the Array class in JavaScript causing issues with for loops While it may not be best practice, I want all objects to have this specific function when including a certain piece of code. I find it strange that when ...

Creating a cucumber feature file from an Excel sheet or any other type of file: A step-by

I currently have an excel sheet containing various scenarios that I need to convert into a feature file. Can you assist me in accomplishing this task? Do you know of any plugins that can help streamline this process? Any guidance would be greatly apprecia ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

Click on the div in Ionic 2 to send a variable

<div class="copkutusu" (click)="kanalsil(kanalid,deneme)" #kanalid id={{ver.channelid}} #deneme id={{ver.channelapikey}}></div> I am requesting kanalid.id and deneme.id in my .ts file. Even though they are the same variable names, they repres ...

Leveraging the Nest JS Validation Pipe in combination with the class-transformer to retrieve kebab-case query parameters

Can someone help me with using the Nest JS Validation Pipe to automatically transform and validate my GET Request Query Params? For example: {{url}}/path?param-one=value&param-two=value In my app.module.ts, I have included the following code to impl ...