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

Having trouble with material-ui installation in React, Redux, and React-Router project

Guide: https://i.stack.imgur.com/k1UMV.png Due to using redux and react router, incorporating MuiThemeProvider at the top of the chain is a bit challenging. What would be the most effective method to integrate this particular library? This is my ReactDO ...

Is it feasible to update just one key within an exported type using setState in TypeScript?

Recently, I decided to dive into Typescript within my React App and encountered an error that has left me stumped. I'm wondering if it's possible to access a specific key in an exported type and modify its value? Here is how I've exported ...

Binding arguments to child functions within Vue components

When working with React, it's a common practice to bind parameters for child components in the following manner: <Child onChange={e => doThing(complex.variable.inParentScope[3], e.target.value)} foo="bar" /> In Vue, I want to ach ...

Unlock the Power of Rendering MUI Components in ReactJS Using a For Loop

Hey there! Hope everything is going well. I've been working on a fun project creating an Advent/Chocolate Box Calendar using ReactJS. One challenge I'm facing is figuring out how to iterate over a for loop for each day in December and render it ...

Connecting extra parameters to an event listener

Scenario: I am facing a situation where my event handler is already receiving one parameter (an error object). However, I now need to pass an additional parameter when binding the event handler. I am aware of the bind() method, but I am concerned that it ...

Transforming intricate JSON data into a structured table format

I'm struggling to transform the nested JSON data into an HTML table, but I keep encountering an error. I'm uncertain about where I may have made a mistake. Could it be related to how I am trying to access the array within the object? Here' ...

Exploring the intricacies of node.js module 'config' and its configuration files default.json, production.json, and uncovering issues with a specific "Configuration property"

https://github.com/node-config/node-config Here is a quote from GitHub: To install in your app directory, follow these steps: $ npm install config $ mkdir config $ vi config/default.json" The overview explains the installation process and mention ...

In what ways can I leverage the functionalities of an AngularJS directive to delay the display of content until a user clicks on it?

Our rental application utilizes an API call to populate an array, triggering an ngRepeat and generating a list of divs displaying basic rental property information. Upon clicking a specific property, another API call is made to populate an interior ngRepe ...

``There seems to be an issue with the Express app when trying to access it

I have set up an express app that I want other devices on the same WIFI network to access without requiring internet connectivity. The main computer hosting the app is assigned with a fixed IP address: 192.168.1.60 In my server.js file, I have included t ...

Guide on incorporating a JS file in a React application

I recently obtained a template for my website that includes the following JS file which is being called from my React component. !(function($) { "use strict"; // Hero typed if ($('.typed').length) { var typed_strings = $(&quo ...

ngPrime table column selection and data extraction

I am looking to extract multiple columns from a table. Can anyone suggest the best approach for this? Does NGPrime offer any functionality for achieving this task? Appreciate your help! ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

What is the best way to incorporate child nodes when selecting dynamically generated elements through JavaScript?

Currently, I have buttons being dynamically generated on the page using plain JavaScript. For example: <button class="c-config__option c-config__option--button c-config__option--pack" data-index="0"> Item 1 <span>Subtext</span> ...

Retrieving exclusive npm packages from an npmjs user

I am currently facing a challenge with transferring all of our npm modules from npmjs.com to a new location. The issue is that our modules are saved under a private npm user account, making it difficult for me to programmatically access and consume all the ...

AngularJS Expandable Table - Unlocking Limitless Possibilities

Take a look at the code snippet below: <tbody> <tr ng-repeat-start="ticket in tickets"> <td> <button ng-if="ticket.expanded" ng-click="ticket.expanded = false">-</button> <button ng-if="!t ...

Retrieve the HTML tags following the modification of my information in ASP.NET

Apologies for any language errors, I am new to asp.net development. 1- I have a table with dynamically created rows and columns based on user selection of row and column numbers. 2- Each row in the table has the following controls: A- One textbox, one l ...

Convert a div into a clickable link using JavaScript without using too many classes or any ids

After using shortcodes generated by functions.php in a WordPress parent theme, I have come across the following HTML code: <div class="pricing-table-one left full-width "> <div class="pricing-table-one-border left"> <div class=" ...

Showing JSON object in an Angular 2 template展示JSON对象在模

When I execute the following code: stanservice.categoryDetail(this.params.get('id')) .then((data) => { this.category = JSON.stringify(data.res.rows[0]); console.log(JSON.stringify(data.res.rows[0])); }) .catch((error) => { ...

using flexbox in react does not automatically resize

I am attempting to create a layout where the screen is split into two sections - one green block taking up 1/4 of the screen and one yellow block taking up 3/4 of the screen using react.js. However, when I tried implementing the code below, both blocks end ...

Is there a way to verify the presence of data and halt code execution if it is not found?

In my data, there is a table containing a total of 5 links. The first 2 links can vary in availability as they are dynamic, while the last 3 links are static and are always displayed. The dynamic links' data is deeply nested within the state object, s ...