javascript to retrieve data by reducing

Here is the code snippet I am working with:

var points = 4;
var yModifier = [];
for (var i = 0; i <= points; i++) {
    yModifier.push([]);
};
yModifier.forEach(
    (a, j) => {
        var start = j; 
        var end = start + points; 
        for (var i = start, k = 0; i <= end; i++, k++) {
            yModifier[j].push([k, i])
        };
    }
);
console.log(yModifier);

This code produces the following output:

0: [[0,0],[1,1],[2,2],[3,3],[4,4]]
1: [[0,1],[1,2],[2,3],[3,4],[4,5]]
2: [[0,2],[1,3],[2,4],[3,5],[4,6]] 
3: [[0,3],[1,4],[2,5],[3,6],[4,7]]  
4: [[0,4],[1,5],[2,6],[3,7],[4,8]] 

I want to modify the forEach section to achieve the following desired output:

0: [[0,0],[1,1],[2,2],[3,3],[4,4]]
1: [[0,-1],[1,0],[2,1],[3,2],[4,3]]
2: [[0,-2],[1,-1],[2,0],[3,1],[4,2]] 
3: [[0,-3],[1,-2],[2,-1],[3,0],[4,1]]  
4: [[0,-4],[1,-3],[2,-2],[3,-1],[4,0]] 

Answer №1

let totalPoints = 4;
let yValues = [];
for (let index = 0; index <= totalPoints; index++) {
    yValues.push([]);
};
yValues.forEach(
    (array, j) => {
        let startValue = j; 
        let endValue = startValue + totalPoints; 
        for (let i = startValue, k = 0; i <= endValue; i++, k++) {
            yValues[j].push([k, k - j])
        };
    }
);
console.log(yValues);

Answer №2

It appears that the values follow a pattern of [col, col - row]:

let totalPoints = 4;
let yChanges = Array.from({ length: totalPoints + 1 }, function(_, row) {
  return Array.from({ length: totalPoints + 1 }, function(_, col) {
    return [col, col - row];
  });
});
console.log(yChanges);

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

Creating a dynamic jQuery method to apply validation rules to multiple fields

I am currently utilizing the jQuery validation plugin to validate a dynamically generated form. Specifically, I have multiple email input fields created within a PHP loop: <input type="text" name="customer_email_<?=$i?>" value="" id="customer_ema ...

Conceal a specific class from being seen by another class of the same name upon clicking

I have a webpage with multiple images all sharing the same class name. When I try to hide a specific image by clicking on it, all images with that class are affected. Even though I used PHP to display the images on the webpage, I haven't been able to ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Improving the visualization of large GPS tracks on Google Earth Plugin

I need to display GPS routes on Google Earth using the Google Earth API. However, with approximately 20,000 points per route, the performance is not optimal. The code I have implemented successfully draws the tracks but struggles with rendering time and tr ...

After the page has finished loading, the JavaScript code is not able to

I have created a dynamic jobs list from a database that includes conditional salary reporting based on union type. I decided to build the dataset in the page load section of the CS page for output to a label on the ASPX page to handle the conditional state ...

What is the best way to navigate through an XML document within the DOM of an HTML

I am facing an issue with HTML code. My goal is to navigate through an XML document directly from within the HTML code. Here is the XML code: <?xml version = "1.0"?> <planner> <year value = "2000"> <date month = "7" day = " ...

Exploring a multitude of data within a hefty json log document using node.js

I am dealing with a JSON file named sensorlogs.json that contains data from different sensors transmitting at varying frequencies. The timestamps in the file are not in order and one sensor may have missing entries. The goal is to analyze each sensor&apos ...

Balanced-JS encounters a 404 error

I am currently testing out the code sample provided in the following link: https://github.com/balanced/balanced-js After following the README instructions, I was able to get my local server up and running. However, when I visit the website and try to tok ...

angular js sorting JSON objects by ID

I am having trouble sorting and displaying data with AngularJS. I have added a sort option to my table, but it does not seem to be working properly. Could you please review my JSON data? [ { "id":143, "companyName":"XC", "dividendIn ...

Determine the total number of selected items in MagicSuggest when it loses focus

I have been working with MagicSuggest and I am currently facing an issue where I need to retrieve the length of selections on a blur event. Interestingly, my code functions perfectly fine when a new selection is added using the ENTER key, but it fails when ...

Combining a form and table on a single webpage, I am curious how to utilize the form to update the table effectively using Express and Node.js

Seeking guidance in website development as I face a particular challenge. I aim to create a dynamic search page for a website. The form should allow users to select a location or category, with the same page updating with relevant results. Despite succes ...

Can a directive be designed to function as a singleton?

Our large single page app includes a directive that is utilized in various locations across the page, maintaining its consistent behavior and appearance each time. However, we are experiencing an issue with this directive due to the ng-repeat it contains, ...

Update database upon drag-and-drop using jQuery

I have a dataset (shown below) that undergoes sorting by 'section'. Each item is placed into a UL based on its section when the page loads. My goal is to automatically update the section in the database when a user drags an item to a different s ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Tips for inserting HTML into elements using Angular

Recently, I delved into Angular and decided to experiment with Ajax by fetching a document to display on my webpage. The process worked flawlessly, but now I face a new challenge: injecting HTML content into a DOM element dynamically. Typically, this task ...

Transform JSON headers and rows into Object keys using Node.js

I am currently working on retrieving data from an API in JSON format using Node JS. The JSON data consists of headers and rows, including information such as "Vendor, Price, SKU, Error" (see the attached screenshot). I am looking to structure this data int ...

How can I extract the value of the first element in a dropdown using Javascript?

Imagine there is a dropdown menu with an unspecified number of options: <select id="ddlDropDown"> <option value="text1">Some text</option> <option value="text2">Some text</option> <option value="text3">Some ...

There is a lag in the loading of css stylesheets

We created a single-page company website that utilizes three different stylesheets connected to the index.html. By clicking a button, users can switch between these stylesheets resulting in changes to colors, images, and text colors. However, Issue 1: The ...

Unable to retrieve the saved user from the Express.js session

Below is the code in question: app.post('/api/command', function (req, res, next) { var clientCommand = req.body.command; console.log("ClientCommand: ", clientCommand); if (!req.session.step || req.session.step === EMAIL) { ...

Steps to store user input into an array and subsequently combine the stored input:

I am currently working on a form that consists of two text boxes: Task and Description. My goal is to be able to log the input from both boxes and save it via a submit button. For example: Task: do laundry Description: do a buttload of laundry (idk lol) I ...