How to eliminate repeated elements in an array object using TypeScript

What is the most efficient method for eliminating duplicate entries?

0: { taxType: 9, taxCode: "a", taxValidFrom: "01 Jan 2020 00:00:00.000", taxDesc: "a", …}
1: { taxType: 9, taxCode: "C", taxValidFrom: "03 Jan 2020 00:00:00.000", taxDesc: "C", …}
2: { taxType: 9, taxCode: "a", taxValidFrom: "04 Jan 2020 00:00:00.000", taxDesc: "a", …}
3: { taxType: 9, taxCode: "C", taxValidFrom: "05 Jan 2020 00:00:00.000", taxDesc: "C", …}
4: { taxType: 9, taxCode: "B", taxValidFrom: "06 Jan 2020 00:00:00.000", taxDesc: "B", …}

I aim to create an array that contains unique entries based on both date and tax code.

If the tax code is C, only the entry with the date "05 Jan 2020 00:00:00.000" should remain, as this is closest to today's date (06/01/2020).

Answer №1

To iterate through each object in the array, you can either push a new object or replace the existing one.

Here is an approach to achieve this:
1. If the taxcode is not already present in the final array, add the new object to the array.
2. If the taxcode is already in the final array, compare the dates of both objects and keep the latest date.

Recommendation:
An alternative solution is to use the reduce function for the same purpose.

function updateArray(arr) {
    return arr.reduce((acc, curr) => {
        const elementIndexInArray = acc.findIndex(a => a.taxCode === curr.taxCode);
        if(elementIndexInArray === -1) {
            acc.push(curr);
        } else if (new Date(acc[elementIndexInArray].taxValidFrom) < new Date(curr.taxValidFrom)) {
            acc.splice(elementIndexInArray, 1, curr);
        }
    
        return acc;
    }, []);
}

var data = [
    { taxType: 9, taxCode: "a", taxValidFrom: "01 Jan 2020 00:00:00.000", taxDesc: "a"},
    { taxType: 9, taxCode: "C", taxValidFrom: "03 Jan 2020 00:00:00.000", taxDesc: "C"},
    { taxType: 9, taxCode: "a", taxValidFrom: "04 Jan 2020 00:00:00.000", taxDesc: "a"},
    { taxType: 9, taxCode: "C", taxValidFrom: "05 Jan 2020 00:00:00.000", taxDesc: "C"},
    { taxType: 9, taxCode: "B", taxValidFrom: "06 Jan 2020 00:00:00.000", taxDesc: "B"}
];

console.log(updateArray(data));

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

Navigating in express

Here is the structure I am working with: server.ts routes/ index.ts homeRoute.ts In server.ts: let app = Express(); app.use(router); In routes/index.ts: const routes = Router(); export default function router() { routes.use('/home' ...

Angular: bypassSecurityTrustHtml sanitizer does not render the attribute (click)

I'm facing an issue where a button I rendered is not executing the alertWindow function when clicked. Can anyone help?: app.component.ts: import { Component, ElementRef, OnInit, ViewEncapsulation } from '@angular/core'; import ...

How to update keys within a jsonb object in Postgresql recursively

Given the datamodel provided: create table test ( id int primary key, js jsonb ); insert into test values (1, '{"id": "total", "price": 400, "breakdown": [{"id": "product1", "pri ...

Discovering the optimal method for modifying the state of an object within Object-Oriented Programming using Typescript

I have implemented Object Oriented Programming in my project and I am exploring ways to effectively change the state of an object while ensuring its integrity. Although I have created a code snippet for this purpose, I am curious if there are more optimize ...

Troubleshooting Next.js 14.1 Pre-rendering Issue: A Step-by-Step Guide

I just updated my Next.js from version 14.01 to 14.1 and encountered an error during the build process of my application. How can I resolve this issue? The error message reads as follows: Error occurred while prerendering page "/collections". For more inf ...

What makes the Express - Request.query type definition unique? It's recursion with ParsedQs

The request.query object is of type ParsedQs, which is defined as: interface ParsedQs { [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[] } My interpretation of each type is as follows: A value is ...

What type of event does the Input element in material-ui v1 listen for?

I'm currently grappling with material-ui v1 as I search for the appropriate event type for input elements. Take a look at the code snippet below: <Select value={this.numberOfTickets} onChange={this.setNumberOfTickets}> .... Here is the impleme ...

Building hierarchical comments in React Native

I'm currently involved in a React Native project that includes a Nested comment section. These comments are retrieved as JSON data and displayed using a FlatList. const App = () => { const [isLoading, setLoading] = useState(true); const [data, ...

Steps to retrieve a list from a JsonArray containing objects

Is there a way to convert the response.getBody from the above call into an array? I want to extract only the array "data" from the JSON as a list. JSON: { "totalValue": 21, "data": [ { "id": 1, ...

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

Retrieving a specific document from an array that meets a specific query using MongoDB in JavaScript

I have a collection of data stored in MongoDB structured like this: users: { { user_id: 1000, activities: [ {id: 1, activity: 'swimming'}, {id: 2, activity: 'running'}, {id: 3, activi ...

What is the best way to create a dynamic sitemap in Next.js version 14?

I've encountered an issue with the code snippet I'm using for a dynamic sitemap on my blog post website built with Next.js 14. While it works perfectly fine in development, it fails to generate a dynamic sitemap in the build or production environ ...

verify that the labels on the buttons within the array are accurate

I have 5 buttons arranged in an array. I want to hide them randomly until their text matches cevapLabel.Text. How can I check the text of all the buttons? For example: while allButtonsText != cevapLabel.Text {} This is the initial code snippet: @IBActi ...

TextView influenced by Res/Arrays

My current task involves populating a listview with data from a JSON object, which is working properly. setListAdapter(new ArrayAdapter<String>(this, R.layout.list_items, name){ @Override public View getView(int position, View co ...

Having trouble building the React Native app after adding react-native-vector icons?

A recent project I've been working on involved adding react-native-vector-icons using react-native 0.63.4. However, during the build process, I encountered an error when running the command npx react-native run-ios in the terminal. The warnings/errors ...

Tips for resolving Error: ENOENT - file or directory not found:

As a newcomer to Gatsby, I am currently following this tutorial hosted at . After executing the 'gatsby develop' command, everything appears to be successful. However, I encounter the following error: Error: ENOENT: no such file or directory, op ...

Using array elements again in a different array declaration

In my attempt to define an array in bash, I aim to use the values from another array as the name for the new array and assign its values from a dynamically populated array. Below is an example of the current code: adduser() { declare -i segment=$1 s ...

The moduleResolution setting is missing in the tsconfig.json file generated by Next.js TypeScript

Currently, I am in the process of migrating my existing Next.js project to TypeScript. To do this successfully, I have installed various TypeScript related packages by running the following command: npm install --save-dev typescript @types/react @types/nod ...

Saving Class Instances in an Array

I have been struggling to store objects with a username and password from the "Driver" class into an ArrayList. However, when I attempt to print out every value in the array for testing purposes, it only displays the last value entered, repeatedly. I have ...

Exploring sdcard files in your Ionic 3 application

I am a newcomer to Ionic 3 and facing an issue while trying to upload documents from a device. I have used Android permissions for storage access but I am only able to access the internal storage of the device. My goal is to access files from the SD card. ...