Using values from a preexisting array to generate new arrays in JavaScript

I'm currently facing a challenge in JavaScript where I need to generate arrays based on the values of another array.

For instance, I have an array of dates in string format (dates) listed below:

["30/09/2015", "31/10/2015", "30/11/2015", "31/12/2015"]

Additionally, I have an Object that represents various bank accounts (balancesSortByAccId) as shown:

Cash - (Array size: 3)
id: 1, date: "30/09/2015", balance: 30
id: 2, date: "31/10/2015", balance: 50
id: 3, date: "30/11/2015", balance: 100

Natwest - (Array size: 2)
id: 4, date: "30/11/2015", balance: 400
id: 5, date: "31/12/2015", balance: 200

My goal is to create arrays for each date in the 'dates' array by retrieving balances from the accounts in 'balancesSortByAccId'. Here's what I aim to achieve:

[30, 50, 100, null]
[null, null, 400, 200]

If you have any suggestions on how I could accomplish this, please let me know!

UPDATE: You can view my jsfiddle code here - https://jsfiddle.net/gx8bLehb/

Answer №1

To streamline the process, consider organizing your `cash` and `natwest` arrays into a sorted hash based on date, like renaming it to `balancesByDate`:

var balancesByDate = _.groupBy(cash, function(entry) {return entry.date});

Then, utilize an array's `map()` method, such as one from lodash, to loop through the `dates` array. For each date, search for the account line in the `balancesByDate` hash. Return the `balance` property using the `map` method.

dates.forEach(function(date){
  if (balancesByDate[date]) {
    results.push(_.map(balancesByDate[date], function(line){
       return line.balance;
    }));
  } else {
    results.push(null);
  }
});

It's important to note that your data set might have duplicate balances for a day. Consider this factor while planning (my code returns an array for each day).

https://jsfiddle.net/hdpuuc5d/1/

Answer №2

An implementation using vanilla JavaScript and a date helper object:

const datesArray = ["30/09/2015", "31/10/2015", "30/11/2015", "31/12/2015"];
const datesObject = datesArray.reduce((acc, date, index) => {
  acc[date] = index; 
  return acc;
}, {});
const accountBalances = {
    Cash: [
        { id: 1, date: "30/09/2015", balance: 30 },
        { id: 2, date: "31/10/2015", balance: 50 },
        { id: 3, date: "30/11/2015", balance: 100 }
    ],
    Natwest: [
        { id: 4, date: "30/11/2015", balance: 400 },
        { id: 5, date: "31/12/2015", balance: 200 }
    ]
};
const finalResult = {};

Object.keys(accountBalances).forEach(key => {
    finalResult[key] = Array.from({ length: datesArray.length }, () => null);
    accountBalances[key].forEach(entry => {
        finalResult[key][datesObject[entry.date]] = entry.balance;
    });
});

document.write('<pre>' + JSON.stringify(finalResult, 0, 4) + '</pre>');

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 state value is not being updated by the useReducer function

Hey there! I had this idea to add a black transparent overlay with text to my page while it's waiting for data from the server. I wanted the overlay to cover 100% of the page and be 30% black with the text "Loading ...". I set it up using useState, b ...

What steps should be followed to set up Selenium WebDriver to accept command line options using Node.js?

I'm currently working with Selenium WebDriver through Node.js and I have a set of resources that I'm not sure how to interpret for my specific objective (here and here). At the moment, all my tests are running successfully as intended but now I w ...

Retrieve contact emails from an array using the iOS people picker

Recently, I've been facing a minor issue while trying to extract emails from a contact in my people picker on iOS. Previously, everything was working smoothly prior to Swift 2.0. My goal is to retrieve these emails and store them in a string array. Ho ...

Having trouble with my form validation for a university project. Not sure if it's a problem with the JavaScript or HTML

I had attempted to simplify things, but I'm at a loss as to what could be causing the issue. I'm uncertain if the return command is functioning properly or if the button is creating a problem, but I can't seem to pinpoint the exact issue. M ...

The option to clear searches is missing from the iOS interface

My application is designed to perform searches using post codes, and for the most part, it functions properly. However, I have encountered an issue where the clear icon on the right-hand side of the field does not display in certain browsers. To investiga ...

dividing a matrix into sections (JAVA)

tag: I am working with an Array[n][n] where the size, n, is a power of two, and I am looking to recursively manage the quadrants of the array. Is there a way in Java to select a segment of the array that covers the elements from [0 to (size/2)][0 to (size ...

What are some methods for bypassing the use of a keypad for a specific input

I have a mobile app built with Ionic. When the user taps on any input field, the keypad opens which works well. However, I have a datepicker with an input field where I want to prevent the keypad from opening. How can I achieve this? <div class="col" ...

Issue encountered when attempting to modify the directive when the drop-down list is changed in AngularJS

Experiencing issues updating the directive when the drop down list is changed using AngularJS. Below is my application code: HTML Code <div ng-app="myApp" ng-controller="MyCtrl"> <select ng-model="opt" ng-options="font.title for font in font ...

Preserve the table's state even after submitting the form

My php page initially displays a table by default, which is: echo "<table class='tftable' border='1' id='table_L'>"; There is also another table: echo "<table class='tftable' border='1' id=&apos ...

When a label or checkbox is clicked, the absolute positioning triggers a sudden jump to the top of the containing div

Encountering an issue where the user is taken to the top of a scrollable div (absolute position) when clicking a label/checkbox. Code Tried different approaches on an onclick event for each of the 4 labels below, but unfortunately none of them are effect ...

Execute an HTTP POST request to the Node server, sending an empty object

For my project, I am attempting to send an HTTP Post request to my Node server from an html form. Despite using Body Parser and setting it up correctly, I am facing an issue where the req.body on my server is returning as an empty object. Can anyone prov ...

Error: Uncaught [🍍]: The function "getActivePinia()" was invoked without an active Pinia instance present. Ensure that you have called "app.use(pinia)" before attempting to utilize a store

I encountered an issue while trying to access a store in Pinia for my Vue web application. Despite installing Pinia and setting app.use(createPinia()), I keep receiving the following error message: Uncaught Error: [ ...

Click on the button to reveal the hidden content within the div, and then smoothly scroll down to view

I have a footer div that is present at the bottom of every page on our site. I've added a button to expand this div, but I'm looking for a way to automatically scroll the page down so that the user can view the expanded content without manually s ...

Establishing the Access-Control-Allow-Origin

I have a basic .NET web service: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = "http ...

Managing arrays within nested structures

I am currently working on creating an array of structures with an array inside. However, I am facing an issue where only the first elements of both arrays are getting initialized with values. Can someone please provide assistance with this problem? #inc ...

JavaScript has issues with undefined array elements

Even though there is data in bindInfo, the array elements in Bind are showing as undefined. Any recommendations? let bindinfo = { clientid: 1, clientname: 'Web Client', nowutc: now_utc, bindlist: Bindings(this.props.bindDetails) ...

Calculate the height of the document in Python by using the function $(document).height()

I am looking to retrieve the height of a document for different URLs, essentially creating a JavaScript function similar to $(document).height() that works across all pages. Any suggestions on how I can accomplish this task? I have experience with Python ...

Using JQuery to Identify the Clicked Div Container

Currently working on a JQuery script to determine which specific div box was clicked, but running into some issues. I understand that there are other approaches to achieve this by directly invoking functions upon clicking a div box, but I want to first ide ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

having difficulty in transmitting json data using ajax

Struggling to send JSON data to my PHP script via AJAX and it keeps returning NULL as a response. The jQuery script I'm using involves creating a JSON data on a click event and then attempting to send it to the PHP script. Here's a snippet of the ...