Traversing through an array of objects using a for loop and accessing each object within the array

const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 0.0 },
  { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];

function getAllWithdrawals(bankAccounts) {
  let newArr = [];
  for (let acc of bankAccounts) {
    if (acc.withdrawals) {
      newArr.push(acc.withdrawals)
    } else if (!acc.withdrawals) {
      newArr.push(0);
    }
  }
  return newArr;
}

I am attempting to access the array objects and find a way to extract the withdrawal amounts from each object that has them. I aim to total these withdrawal amounts and store them in the blank array called "newArr". Do I require another for loop to achieve this task? My main objective is to iterate through the objects, identify those with withdrawal arrays, add up the amounts within those arrays, and then push the grand total into the "newArr".

Answer №1

Presented below is a solution in functional programming leveraging map reduce methodology:

const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] }, { id: 3, name: "Joshua", balance: 18456.57, deposits: [4000, 5000, 6000, 9200, 256.57], withdrawals: [1500, 1400, 1500, 1500], }, { id: 4, name: "Candy", balance: 0.0 }, { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] }, ];

function getAllWithdrawals(bankAccounts) {
  return bankAccounts.map(obj => {
    return obj.withdrawals ? obj.withdrawals.reduce((sum, num) => sum + num, 0) : 0;
  });
}

console.log(getAllWithdrawals(bankAccounts));

Output:

[
  300.68,
  0,
  5900,
  0,
  100
]

Docs:

Shown below is an improved version where the function accepts either the 'deposits' or 'withdrawls' key:

const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] }, { id: 3, name: "Joshua", balance: 18456.57, deposits: [4000, 5000, 6000, 9200, 256.57], withdrawals: [1500, 1400, 1500, 1500], }, { id: 4, name: "Candy", balance: 0.0 }, { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100]
}, ]; 

function getSums(bankAccounts, key) {
  return bankAccounts.map(obj => {
    return obj[key] ? obj[key].reduce((sum, num) => sum + num, 0) : 0;
  });
}

console.log({
  deposits: getSums(bankAccounts, 'deposits'),
  withdrawals: getSums(bankAccounts, 'withdrawals'),
});

Output:

{
  "deposits": [
    401,
    1100,
    24456.57,
    0,
    118
  ],
  "withdrawals": [
    300.68,
    0,
    5900,
    0,
    100
  ]
}

UPDATE 1: Requested usage of only for loops incorporated:

const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] }, { id: 3, name: "Joshua", balance: 18456.57, deposits: [4000, 5000, 6000, 9200, 256.57], withdrawals: [1500, 1400, 1500, 1500], }, { id: 4, name: "Candy", balance: 0.0 }, { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] }, ];

function getAllWithdrawals(bankAccounts) {
  let result = [];
  for (let obj of bankAccounts) {
    let sum = 0;
    if(obj.withdrawals) {
      for (num of obj.withdrawals) {
        sum += num;
      }
    }
    result.push(sum);
  }
  return result;
}

console.log(getAllWithdrawals(bankAccounts));

Answer №2

It seems like there might be some confusion in your question, but if you need to calculate the total of all withdrawals, you can follow this approach:

const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 0.0 },
  { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];

function getAllWithdrawals(bankAccounts) {
  let newArr = [];
  for (let acc of bankAccounts) {
    if (!!acc.withdrawals) {
    acc.withdrawals.forEach(withdrawal => newArr.push(withdrawal))
    }
  }
  return newArr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
}

console.log(getAllWithdrawals(bankAccounts))

If you need to sum the withdrawals for each individual object instead, you can use the following code:

const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 0.0 },
  { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];

function getAllWithdrawals(bankAccounts) {
  let newArr = [];
  for (let acc of bankAccounts) {
    if (!!acc.withdrawals) {
        newArr.push(acc.withdrawals.reduce((accumulator, currentValue) => accumulator + currentValue, 0))
    }
  }
  return newArr;
}

console.log(getAllWithdrawals(bankAccounts))

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 best way to extract substrings from a given string for the entire length of the string and then store them in an array?

Trying to extract specific substrings from a string NSString *str = @"M 2 2 C 5 6 7 8 9 1 2 3M 1 2 C 5 6 7 8 9 1 2 3" I am aiming to create an array of substrings such as ["2 2","5 6 7 8 9 1 2 3","1 2","5 6 7 8 9 1 2 3"] Further, I want to associate the ...

Extracting input value using HTML and JavaScript

Is there a way to utilize the content of a form field within a confirmation dialog box that pops up upon submission, as illustrated below? <form action='removefinish.php' method='post' accept-charset='UTF-8'> Role: < ...

Tips for modifying the style of a component within node_modules using its individual vue <style> sections

I am trying to modify the CSS file within the multiselect package, but I don't want to make changes directly in the node_modules folder. Instead, I want to add my custom styles between the style tags of my Vue page. Specifically, I am attempting to ad ...

Is there a way to toggle a command for a specific discord server rather than enabling it for all servers where the bot is present?

I've been working on a Discord bot with multiple commands managed by a custom command handler. However, I'm facing an issue where enabling a command affects all servers the bot is in. How can I implement a system using message.guild.id to toggle ...

Unlock the full potential of ngx-export-as options with these simple steps

Being a newcomer to angular, I am currently working with a datatable to display a set of data. I have successfully implemented the functionality to export the table's data as a PDF using ngx-export-as library. However, when downloading the PDF, it inc ...

Having trouble with passing parameters in AngularJS $state.go?

Having some trouble implementing AngularJS $state.go() with a parameter. It seems to work fine without the parameter, but when I try to pass one in, it's not working as expected. I've looked at several examples and tried different approaches, but ...

Tips for Retrieving Data from a Multi-Dimensional Array

I need help accessing the values in my array and assigning them to variables for later use. I have created an array and used the randomGo() function to generate a random number that corresponds to a pair of numbers within the array. My goal is to assign ...

Just systems that have been positively identified

Greetings! I am currently in the process of creating a small online stock management system using PHP. However, my goal is to restrict access to this web app to only certain systems that I designated. I want to ensure that only the systems under my contro ...

Guide to keeping numerous movie titles in an array with a for loop in Java

I am currently working on a project for my school assignment, where I need to collect multiple movie titles along with the number of copies of each movie and store them in an array. However, every time I enter a new title, it replaces the previous one(s). ...

Trigger the jQuery function once the external URL loaded via AJAX is fully loaded

Currently, I am in the process of developing a hybrid mobile app for Android and I am relatively new to this technology. I have two functions in jQuery, A and B. Function A is responsible for making an AJAX request to retrieve data from 4 external PHP fi ...

The Model.function method is not a valid function that can be used within a router

Currently facing a challenge with my router setup. I have exported the function as shown in the code snippet below. This is the Model I am using: "use strict"; var mongoose = require('mongoose'); var bcrypt = require("bcryptjs"); var Schema = m ...

Update the href tag to javascript: instead of #

Hello, I previously inquired about how to dynamically load a div's content (a URL) by clicking a button instead of loading it on page load. Someone provided me with the following code as a solution: <script type="text/javascript"> function ...

Error: Unable to retrieve the specified ID

One unique aspect of my backbonejs app is the model structure: var Store = Backbone.Model.extend({ urlRoot: "/stores/" + this.id }); This is complemented by a router setup like so: var StoreRouter = Backbone.Router.extend({ routes: { 's ...

Can Authorization be Combined with Filtering in a Node.js RESTful API?

In my current setup, I have a web application communicating with a RESTful API to interact with the database. The frontend of the web app uses Angular HTTP to post/get/put data to the backend, which then manages authentication, interacts with the API, and ...

What is the best way to utilize class labels?

I've encountered an issue I need help with. There are two lists of options in play here. One list has names all starting with 'M', and the other with 'R'. The task is to select specific options, like 'A' and 'C&apos ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

What is the process of sending JSON data from an Express server?

I created a server using express.js and one of the routes is set up like this: app.get("/api/stuff", (req, res) => { axios.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1').the ...

Disable scrolling to the next component until the animation is fully finished with the help of framer

Exploring the world of framer-motion, I am currently working on creating a Starfield effect similar to the one seen on the homepage of Repl.it (logged-out version). Upon loading the website, a mesmerizing starfield emerges with text overlaid. As you scrol ...

repetitive process using values from an array

I have an array called $um with the following elements: $um = array("PHP", "Python", "Java", "C++"); My goal is to display combinations of these elements like this: PHP ------- Python PHP ------- Java PHP ------- C++ Python ---- Java Python ---- C++ Jav ...

Creating a dynamic HTML select form with generated options - tips and tricks

My HTML form includes a script that automatically activates the default "option" (with hard-coded option values). In addition, I have a separate script that dynamically generates "options" based on specific column values in MySQL. The issue arises when s ...