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

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

Using Ruby to convert JSON data into an array

This is an example of JSON code containing job and applicant information { "jobs": [ { "id": 1, "title": "Software Developer", "applicants": [ { "id": 1, "name": "Rich Hickey", "tags": ["clojure", "java", "immutability", "datom ...

What are the steps to ensure a successful deeplink integration on iOS with Ionic?

Recently, I was working on a hybrid mobile app for Android/iOS using Nuxt 3, TypeScript, and Ionic. The main purpose of the app is to serve as an online store. One important feature involves redirecting users to the epay Halyk website during the payment pr ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

Removing blank values from a string following the conversion from char array (using C#)

Suppose we have an array of characters like this: char [] textArray = new char [8]; Next, I assign some values to the array: textArray[0] = (char) 12; textArray[1] = (char) 48; Then I use the operation below: string finalText = string.Join("", textArr ...

Angular - Implementing filter functionality for an array of objects based on multiple dropdown selections

I am currently working on filtering an array of objects based on four fields from a form. These four fields can be combined for more specific filtering. The four fields consist of two dropdowns with multiple selection options and two text boxes. Upon cli ...

What is the best way to merge multiple nested angular flattening operators together?

I am facing a challenge in utilizing the outcomes of Observables from various functions. Some of these functions must be executed sequentially, while others can run independently. Additionally, I need to pass the result of the initial function to some nest ...

How to assign various column values to a PHP array in JSON format from a MySQL database

I am struggling with making a JSON Ajax request and receiving an array in return. After browsing through multiple questions, I came across this code snippet that I edited to fit my problem: var hej[]; function ajax_search(){ $.getJSON('test.php ...

Is there a way to handle null return in case the data is not present?

Is there a way to handle situations where the data I pass is empty, like if(!testimonials) return null? Currently, it just shows an empty array. I'm not sure where to implement an "if-else" rule. AboutUs Page export const getServerSideProps = async ( ...

Implementing TypeScript in an Asp.net Core ReactJS application`s configuration

After using Visual Studio 2022 to create an asp.net core Reactjs project, I discovered that everything was written in javascript instead of typescript. Is there a way to switch this project over to typescript? ...

Pictures are shown using the "text/html" layout

I'm having trouble identifying the error and have decided to carefully examine both the client and server code. It seems likely that there is a bug somewhere in Rails. The issue revolves around the photos being displayed in text/html format. Here&apos ...

Using the hook to implement the useContext function in React

I came across this definition export interface user{ email:string name:string last_name:string } export type UserType= { user: user; setUser:(user:user) => void; } const [user,setUser] = useState <user> ({ email ...

Using ExpressJS with the GET method to retrieve JSON data in conjunction with Angular version 4 and above

This inquiry may be a duplicate, I apologize for any repetition. My objective is to console.log JSON data from the "Server" folder. Please find the attached folder structure below. https://i.stack.imgur.com/uec4O.png server.js const express = require(&a ...

The final piece left in stitching together an array

Issue I have been struggling with this code for some time now and I can't seem to figure out the solution. I am receiving 3 values from inputs and trying to remove all the empty spaces "" in the array, but when I execute the code, it displays the foll ...

What is the best approach to prevent the occurrence of two instances of | async in this particular scenario (version 4.0

Is there a way to achieve the desired outcome in this component without using .subscribe()? I attempted to implement *ngIf="user$ | async as user" but encountered difficulties with it. What is the best approach to create a local variable using user$ | asy ...

Issue with Angular 2 Routing: Unable to find a matching route

Currently, I'm in the process of developing an Angular 2+ application that requires routing. One of the requirements is for the color scheme of the entire app to change based on a URL parameter input. In my app.module.ts file, I have the following co ...

Error: Navbar component cannot access static member

I am encountering the error message Static member is not accessible at this particular point: auth.service.ts export class AuthService { public static get isLoggedIn() { const user = JSON.parse(localStorage.getItem('user')); return (u ...

Is there a way for me to pass the templateUrl data from the parent component to another component

Currently, I am in the process of learning Angular2 and facing a situation where I have a dropdown that appears on multiple pages. Each time it is called, the contents of the dropdown change, but the structure remains the same. This is why I have set it up ...

Guide to extracting the outcomes of a promise array and populating them into a new array using Protractor

I am facing a challenge with transferring data from an array of promises generated by the following code: element.all(by.repeater('unit in units')). It seems to be difficult for me to store this data into another array: element.all(by.repeater(& ...

Setting the value in an Autocomplete Component using React-Hook-Forms in MUI

My form data contains: `agreementHeaderData.salesPerson ={{ id: "2", name: "Jhon,Snow", label: "Jhon,Snow", value: "<a href="/cdn-cgi/l/email-prot ...