Manipulating array objects by replacing values in Typescript

Attempted two different methods to obtain a partial summary within each array object, but unfortunately, both were unsuccessful.

var arr = [
  { "value": 10, "newBalance": 0 },
  { "value": -10, "newBalance": 0 },
  { "value": 15, "newBalance": 0 },
];

let total = 0;
for (let i = 0, l = arr.length; i < l; ++i) {
    total = total + arr[i].value;

    arr.map(item => { item.newBalance = total; return item; });
    // updating all newBalance values with the final total

    arr.map(item => item.newBalance != 0 ? { ...item, newBalance: total } : item);
    // does not correctly update newBalance
}
console.log(arr);  

What mistake am I making in this code?

Answer №1

One way to achieve this in a clean manner is by using reduce within a single loop. It's important to note that the original array remains unchanged as this method returns a new array. However, you can easily assign the new array back to the original if needed.

Utilizing reduce allows you to access the current accumulation, making it convenient to work with the previous values when processing each item.

const arrayWithSummary = arr.reduce((summary, currentLineItem, index) => {
    return [...summary, { ...currentLineItem, newBalance: currentLineItem.value + (summary?.[index - 1]?.newBalance ?? 0)}]
}, [])

You can find the result stored in the arrayWithSummary variable.

https://i.stack.imgur.com/JrhoS.png

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

Differences between ng build --prod and ng --build aot in Angular 7

Recently, I successfully built an Angular 7 application using the command ng build --prod. However, I am now facing a dilemma regarding ng build --aot versus ng build --prod. Our application is currently deployed on ..., and although it runs successfully ...

Using the CdkDragDrop functionality alongside the ngTemplateOutlet

I'm experimenting with the Drag&Drop functionality introduced in Angular Material 7. To make my template more modular, I've utilized ngTemplateOutlet to create reusable components. Each option can either be a primary Thing™ or a nested Thi ...

Utilizing TypeScript generic types as a key for an object

function createRecord<T extends string>(key: T): Record<T, string> { return { [key]: 'asdf' }; } Encountering an issue: The type '{ [x: string]: string; }' is not matching with the expected 'Record<T, st ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

Tips for ensuring a program pauses until an observable is completed within an Angular application

Currently, I am working on a project using Angular. I encountered a situation where a call to the backend is made using an observable to fetch products. Below is an example of how the code appears: getProducts () : Product[] { this.http.get<[]>(this ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...

Updating a boolean value when the checkbox is selected

Hey there! I'm currently working on a project using Angular and have a collection of elements that can be checked, which you can check out here. In terms of my business logic: stateChange(event: any, illRecipe: Attendance){ var state: State = { ...

How can you establish a TypeScript project that employs classes shared by both client and server applications?

I am working on a project that consists of two components: ServerApp (developed with nodejs using NTVS) and BrowserApp (an Html Typescript application). My goal is to share classes between both projects and have immediate intellisense support. Can you pr ...

What is the most effective way to combine quantities when the keys are identical?

Array ( [INV828] => Array ( [0] => shams interior [org_name] => shams interior [1] => INV828 [inv_no] => INV828 [2] => 1556 [productid] => 1556 [3] => E001-4ft [p ...

What is the best way to send two separate properties to the selector function?

My selector relies on another one, requiring the userId to function properly. Now, I want to enhance the selector to also accept a property named "userFriend". However, there seems to be an issue with passing this new parameter, as it only recognizes the ...

Why is it necessary for the required type of a function parameter to be able to be assigned to

From Optional to Required Type const testFunc = (func: (param: number) => void): void => { func(3); }; testFunc((a?: number) => { console.log(a); }); From Required to Optional Type const testFunc = (func?: (param: number) => void): void = ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

The dropdown feature in Bootstrap 5 seems to be malfunctioning in Angular 12

I am facing issues while trying to implement the Bootstrap 5 dropdown in Angular 12. After installing all required packages and adding them to the angular.json file, I still cannot get it to work properly. Even after copying the example directly from the ...

Injecting Dependencies in Angular 2 Without Using the Constructor

Exploring DI in Angular 2 has led me to implement a REST-Client using generic subtypes for concrete Datatypes like this: class RESTClient<T>{ constructor() { var inj = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]); this. ...

Is it necessary to use Generics in order for a TypeScript `extends` conditional type statement to function properly?

Looking to improve my understanding of the extends keyword in TypeScript and its various uses. I recently discovered two built-in utilities, Extract and Exclude, which utilize both extends and Conditional Typing. /** * Exclude from T those types that are ...

What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows: { "status": "success", "response": [ { "id": 1, "name": "SEA BUSES", "image": null }, { "id": 2, ...

Tips for removing a specific dynamic element in HTML using an Angular reactive form

I successfully implemented a dynamic reactive form that allows users to add or delete fields dynamically. However, I am facing an issue with removing the Radio Button (And / Or) from the last row. I would like it to only appear for the first and second row ...

What strategies can be implemented to optimize array searching, remove a value, and reindex the array after the search operation?

Is there a way to optimize array search by unsetting values and re-indexing the array? This was fine when dealing with small amounts of data, but my application is fetching over 2695 web property links from the Google Analytics API! Before displaying these ...

Adding key/value pairs to an array of objects in RxJS Observables can be easily

I currently have an Angular app with state management that retrieves data from a database in observables. Here is an example of the interfaces I am working with: interface Service { id: number, name: string, category_id: number, } interface Category ...

Angular application's HTML Canvas unexpectedly changes to a black color when I begin drawing

Currently, I am developing an Angular application in which users can draw text fields on PDF pages. To achieve this functionality, I have integrated the ng2-pdf-viewer library and created a PDF page component that incorporates an HTML canvas element. Howe ...