Ways to avoid duplicate objects when using the array.reduce method

Here is a function that I need help with:

    range: [number, number] = [135, 145]

    update(property: string, path: string, range: [number, number]) {   
            if (path.split('|').length === 2) {
                const steps = path.split('|')
                
                const addressSteps = steps.slice(0, -1)

                const lastStep = addressSteps[addressSteps.length - 1]
            
                const reducer = (accu, step) => accu[step]

                // We get to the branch you need to update
                const stateBranch = addressSteps.reduce(reducer, state)

                stateBranch[lastStep] = {
                    ...stateBranch[lastStep],
                    [property]: range,
                }

        }),
    )
}

When I call this function...

update(bHbMaleMass, 'haematology|cbc', [135, 145])

...the state gets updated as shown in the screenshot provided.

https://i.sstatic.net/ebons.png

One issue to note is:

  1. The haematology node appears duplicated within the cbc node with the correct updates.

I aim to solely update the cbc node without any duplicates of haematology or cbc nodes.

Thank you for your assistance

Note: This query was previously posted at [Looking for a better way to structure code closed, but it relates specifically to one of the solutions suggested in the response.

Answer №1

Alter the code

const recentAddress = addressList[addressList.length - 1]

Replace with

const recentAddress = allAddresses.slice(1,2)[0];

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

The 'typeof Environment' argument cannot be assigned to the 'Environment' parameter

Snippet of Code: enum Environment { Production = 'production', Development = 'development', Test = 'test' } export class Config { public constructor(EnvProd: Environment = Environment.Production, EnvEnum = En ...

Optimizing the Angular app for production can lead to the malfunction of specific components

I am currently working on an Angular application and encountering some issues during the compilation process using ng build. When I compile the project for production deployment with the optimization option enabled, I am faced with console errors that prev ...

Creating an Express server using Webpack, TypeScript, and ESM

Hello, I am currently working on a small project using node.js and TypeScript with webpack. Here is a snippet of my tsconfig.json file: tsconfig.json { "compilerOptions": { "lib": ["ESNext"], "target": "ES2020", "module": "NodeNext", "mod ...

Exploring NestJs: The Importance of DTOs and Entities

In my project, I'm currently experimenting with utilizing DTOs and Entities in a clever manner. However, I find it more challenging than expected as I develop a backend system for inventory management using NestJs and TypeOrm. When my client sends me ...

The TypeScript compiler is unable to locate the name 'MediaRecorder'

I am currently working on a Vue3.js web project using TypeScript. I am facing an issue where I need to save the user's camera and microphone data after they click a button. Running my project with node version 16.14.0, I encountered a problem with Med ...

Is there a way to trigger the click event in the week view of an Angular 2+ calendar?

https://i.sstatic.net/Vx2x8.png HTML Templates <mwl-calendar-week-view [viewDate]="viewDate" [refresh]="refresh" (click)="weekDayClick($event)"> </mwl-calendar-week-view> In the component file weekDayCl ...

Creating a sophisticated union type by deriving it from another intricate union type

I have a unique data structure that includes different types and subtypes: type TypeOne = { type: 'type-one', uniqueKey1111: 1, }; type TypeTwo = { type: 'type-two', uniqueKey2222: 2, } type FirstType = { type: 'first&apo ...

Leveraging Firestore Errors within Cloud Functions

Is it possible to utilize the FirestoreError class within Firebase cloud functions? The goal is to raise errors with a FirestoreError type when a document or field is not found in Firestore: throw new FirestoreError(); Upon importing FirestoreError using ...

TS1316 Error: You can only have global module exports at the top level of the file

Encountering difficulties while trying to compile an older typescript project that I am revisiting. The build process is failing due to an issue with q. I suspect it may be related to the tsc version, but no matter which version I try, errors persist. Som ...

The TS type guard fails to identify a non-empty property in a class object

Encountering an issue with TypeScript that involves a class property typed as AmplitudeFeatureFlags | {} = {}; initialized as an empty object. Attempting to retrieve a value from this class property using a method that takes in a property name argument of ...

Retrieving data from array services in Angular using Typescript

I need help retrieving data from an array in my services using a get function. I've tried using the .filter and .find functions, but I'm struggling with the execution and haven't been able to retrieve the data successfully. I know this may b ...

Cannot assign a value of type X to type T

export function retrieveEmpty<T extends { data: any[] }>(): Observable<T> { const response: T = { data: [] }; return of(response); } encountering a compilation error stating Type '{ data: undefined[]; }' is not compatible with ...

Converting an object into an array using React and TypeScript

Extracted from a form is an object with input, output, and outputType fields that can vary between number, string, and boolean types. To display the information in a table without the output type, I have created a mapped obj. However, I also need to prese ...

Tips on successfully passing a property with a generic type T using @Input() in a component (e.g. @Input() ItemsList: T[] = [];)

Currently, I am in the process of developing a component that takes an @Input() property named itemList, shown below: @Input() ItemList: T[] = []; Is there a method available to transfer the @Input property of type T from the parent component to the chil ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

Executing 'npx tsc --version' displays a distinct TypeScript version within the virtual environment

I need to run npx tsc on my project in both my host and guest operating systems. However, the guest OS is using an older version of tsc that I cannot identify. Here is my setup: Host OS: Windows 10 Guest OS: Debian 9 I am using VirtualBox with the "shar ...

What is the correct way to properly parse JSON attributes containing slashes?

I have 2 Custom Interfaces: DataModel.ts export interface Entry{ id: number, content: Note } export interface Note{ message: string } These interfaces are utilized in typing the HttpClient get request to fetch an array of Entries: DataService.ts getE ...

How do I bind a div element in Angular 2?

<div *ngFor="let city of israelCitieService.data|mychoosedcities:wordSerched;let i=index" </div> I am trying to find out how to access the length of the array generated by the pipe. The index (i) is only accessible within the div element. Ho ...

Transform the object into a function that returns the object while still maintaining the casting

I have this item: const five: { quantity: number } = { quantity: 5, } I would like to transform it into a function that yields the same item, like this: const five = () => ({quantity: 5}) Is there a way for me to reuse the casting to ensure the re ...

Observing network events with Ionic 2, RxJS5, and the Cordova network plugin

Is it possible to create an RxJS observable using the fromEvent method based on the Cordova network connection plugin? I am attempting this with Ionic 2. I have noticed that the Cordova network connection plugin offers two events (online/offline). How ca ...