Generating a stacked array using JavaScript

I have an original two-dimensional array representing the full budget for each year, as shown below:

budget = [['2001-01-01', 100], ['2001-01-02', 110], ... , ['2001-12-31', 140]]

Now I want to create subarrays of the budget for specific projects. For example:

project1 = [['2001-01-01', 10], ['2001-01-02', 11]]

This indicates that the project spans 2 days and utilizes 10% of the available budget.

The following function is used to create project arrays:

project1 = [[]];
project1 = new_project(budget, 0, 1, 0.1);

function new_project(origin, start, end, factor) {
    var result = [[]];
    result = origin.slice(parseInt(start), parseInt(end)).map(function (item) {
        return [item[0], parseInt(item[1]) * factor]
    });
    return result;
}

Issue

How can I update my budget array by subtracting the values of the created projects? I need to adjust the budget dynamically using new_project in order to achieve:

budget = [['2001-01-01', 90], ['2001-01-02', 99],..., ['2001-12-31', 140]]

jsfiddle link

http://jsfiddle.net/gcollect/7DAsL/

Answer â„–1

If you want to update the values in a budget array based on another subset array (like project1), you can utilize the built-in array method forEach(). Here's a custom function called decreaseBudget() that does just that:

function decreaseBudget(original, subset) {
    // Iterate through each item in the subset.
    subset.forEach(function(item, index){
        // Retrieve the original amount from the corresponding item in the original array.
        var originalItemAmount = original[index][1];
        // Update the amount in the original array by subtracting the amount from the subset.
        original[index][1] = (originalItemAmount - item[1]); 
    });
};

To apply this function, pass in the budget and project1 arrays as arguments. This will modify the values within the budget array. You can check out the updated fiddle for reference: http://jsfiddle.net/7DAsL/4/

If you'd rather not alter the original array and prefer to work with a copy, you can use the .slice() method to create a shallow duplicate of the original array. Make changes to this copy inside the decreaseBudget() function and return it instead.

Answer â„–2

Here is the solution I found: http://jsfiddle.net/gcollect/7DAsL/2/

Problem solved!

    function create_new_project(base, begin, finish, multiplier) {
        var finalResult = [
            []
        ];

        finalResult = base.map(function (element) {
            return [element[0], (element[1] * multiplier)]
        });
        for (var index = 0; index < finalResult.length; index++) {
            base[index][1] = parseInt(base[index][1]) - parseInt(finalResult[index][1]);
        }
        finalResult = base.slice(parseInt(begin), parseInt(finish));
        return finalResult;

    };

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 ES6 modules within JavaScript for exporting uncomplicated variables

In my JavaScript code, I have defined pageId = 3 in one file and socket = io() in another file. Now, I need to access these variables in other files. I am considering using ES6 modules for this purpose, but I am unsure of how to proceed. Currently, the s ...

Experiencing a Node.js application issue with the error message "ERR

I'm encountering some serious challenges with a Node.js app that I am developing using Express, MongoDB, and Mongoose. Everything seemed to be functioning correctly last night when I used nodemon server.js to start the server. However, I'm now fa ...

"Enhance Your XYChart with a Striking Background Image Using Amchart

let chart = am4core.create("chartdiv", am4charts.XYChart); chart.background.image = am4core.image("/static/img/bar-chart.png") I'm attempting to apply a background image to my chart in Amchart, but unfortunately it's not di ...

Press anywhere on the screen to conceal the AngularJS element

Attempting to create a toggle effect using 2 ng-click functions. One is bound to a button, the other to the body tag. The goal is for my content to show when the button is clicked and hide when anywhere on the body is clicked. However, it seems that Angul ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...

The jQuery element selection feature is not functioning

Within my HTML file, there lies a table with an empty tbody that is dynamically filled by jQuery once the document is fully loaded. The content of the table body is generated using a PHP script, where jQuery fetches the data via a simple GET request. Belo ...

I'm struggling to solve a straightforward jQuery sliding issue

I am struggling to make text slide from right to left on my website. I want the text to appear only when the page loads or refreshes, and then slide off when a link is clicked, revealing new text. Can anyone help me figure this out? http://jsfiddle.net/XA ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...

What steps should be taken to activate eslint caching?

I'm attempting to activate eslint caching by following the instructions in this section of the user guide The command I am using is npm run lint -- --cache=true, and the lint script simply executes a script that spawns esw (which itself runs eslint â ...

My page is experiencing delays due to setInterval

Currently, I am delving into the world of Chrome Extension development and am faced with a roadblock in replacing elements on a live chat page. While most of my tasks are running smoothly, the one thing causing issues is the setInterval option that trigger ...

Are there any methods to alter the current preFilters within jQuery?

Is there a way to access and manipulate the internal jQuery preFilters using the jQuery.ajaxPrefilter() function? In version 1.11.1, I noticed a private preFilters object declared on line 8568, but it doesn't seem like there is a built-in method to in ...

Tips for utilizing the Toggle Slider JS functionality

I'm attempting to change a value using a slider in HTML, here is my approach: html file : <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script scr="./scripts.js" ...

No duplication of Collada material present

I imported a collada model (.dae) into Three.js and encountered an issue with the object's material. Ideally, the material should appear as follows: However, it currently looks like this: The color is not an issue; I can modify the lighting within t ...

Looking to update table content dynamically using jQuery ajax?

I need assistance in creating a dynamic table that can update its content based on the company selected from a dropdown menu. The data should be fetched using AJAX and only display information related to the chosen company. Furthermore, I would like to imp ...

Using a local function within Node.js and referencing it with the <%%> tag in a document

I am currently working with Node.js and attempting to utilize a local function within a document that requires the JSON I send in the res.render. Is there a method to achieve this? Below is an example of how I attempted to implement it: <%local_vari ...

Issue with Foundation 6 not triggering the change.zf.slider event

Hey there, this is my first time posting and I could really use some help... I'm struggling to make the $("[data-slider]").on('change.zf.slider', function(){}); event trigger. I've attempted using the id of the element like so $(" ...

What is the best way to format a date input field so that when a user enters a year (yyyy), a hyphen (-

Need help with date formatting in the format yyyy-mm-dd. Seeking a way to prompt user input for the year and automatically append "-" to the date as needed. Also utilizing a datepicker tool for selecting dates. ...

Receiving input from the user for a 2-D array in a specified format

I have a 2-D array with dimensions 6x6 named A. I am looking for user input in the format illustrated below: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Each 0 represents a position where the user should provide their values. ...

Error: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

Interactive Google Maps using Autocomplete Search Bar

How can I create a dynamic Google map based on Autocomplete Input? Here is the code that I have written: <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></scri ...