What is the best way to transform a for loop using array.slice into a for-of loop or map function in order to generate columns and rows

Experiencing an issue with Angular8. Seeking help to convert a for loop for an array into a loop utilizing either for-of or array.map.

The code in question involves passing an array of objects and the need to separate it into col and row arrays for visualization.


    private pages = [];
    public grid = [];
    public col = 2;
    public row = 2;
    public indexPage = 0;
    private gridSize = this.col * this.row;
    private items = [
        {
          url:'http://url1',
          name:'1',
          active: false,
        },
        {
          url:'http://url2',
          name:'2',
          active: false,
        },
        ...
      ]
ngOnInit() {
    if(this.col === 0 || this.row === 0) {
      this.grid = this.items;
    }else {
      for (let i = 0; i < this.items.length; i+= this.gridSize) {
         let page = this.items.slice(i , i+this.gridSize);
         this.pages.push(page);
      }
      for (let i = 0; i < this.pages.length; i++) {
        let pageUrl = [];
        for(let j = 0; j < this.pages[i].length; j+=this.col) {
          let urls = this.pages[i].slice(j , j+this.col);
          pageUrl.push(urls);
        }
        this.grid.push(pageUrl);
      }
    }
  }

Output from object with col = 2; row = 2:

pages --> (2) [Array(4), Array(3)]             
              --> (0) [{...},{...},{...},{...}] 
              --> (1) [{...},{...},{...}]       

grid --> (2) [Array(2), Array(2)]
            -->(0) [Array(2), Array(2)]   
                   --> (0)[{...},]{...}]    
                   --> (1)[{...},]{...}]    
           --> (1) [Array(2),Array(1)]   
                   --> (0)[{...},{...}]     
                   --> (1)[{...}] .        

Although output is accurate, there's a tslint error on the for loop:

Expected a 'for-of' loop instead of a 'for' loop with this simple iteration

Note: The rows and columns are customizable

Answer №1

Here is a way to transform your regular loops into for-of loops:

    const elements = [];
    let counter = 0;
    const limit = 10;

    while (counter < limit) {
        elements.push(counter);
        counter++;
    }

    for (const element of elements) {
        console.log(element);
    }

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

Highlighting the home page in the navigation menu even when on a subroute such as blog/post in the next.js framework

After creating a navigation component in Next JS and framer-motion to emphasize the current page, I encountered an issue. The problem arises when navigating to a sub route like 'localhost:3000/blog/post', where the home tab remains highlighted i ...

Executing the command "node-gyp rebuild" will produce a build log in the file "build_log.txt", and any errors will be redirected

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e5e7e3d0a9bea1a4bea0">[email protected]</a> install /var/www/html/my-app/node_modules/uws node-gyp rebuild > build_log.txt 2>&1 || exit 0 Error: There ...

Consecutive API requests within React context

When I'm developing locally, I encounter the error message Error: Rendered more hooks than during the previous render. in my application when refreshing the page. I suspect this is happening because I am making two calls within my provider. The first ...

Attempting to update Typescript on Linux Mint using npm

I am currently using typescript 2.1.4 and npm version 6.7.0. Realizing that 2.1.4 is quite outdated, I decided to try and update it. Here are the steps I took, which unfortunately did not work: $ sudo npm update -g typescript $ tsc --version Vesion 2.1. ...

Is it possible to execute TestCafe tests using TypeScript page objects that have not been utilized?

While working with TestCafe, I am implementing tests using the Page Objects pattern. I have already written some page objects in advance, even before their actual usage, as I am familiar with the page and know what to anticipate. However, when attempting ...

Tips for combining Angular 2 with a current J2EE Spring project and deploying them on the same PORT

I currently have a project with Spring on the back-end and AngularJS 1 on the front-end. When I start the Spring server, it only opens one port for me: 8080 which allows me to access REST APIs and the AngularJS front-end components. https://i.stack.imgur. ...

Improving the Sum of Pairs solution on Codewars

Seeking assistance in optimizing a solution for a problem that has already been identified. However, the existing code is not efficient when dealing with large arrays - view the problem on codeWars : Sum of Pairs Below is the current code snippet: var s ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

Is it possible that React useState is not allowing a default value to be set in this case?

In my chart component, I have the functionality to show/hide specific lines. To keep track of active lines, I maintain an array called activeKeys in a state. Initially, I populate this array by calling a function named getKeys, which takes an array of data ...

Steps for utilizing a Get() method to view a response within Angular

I am having trouble with implementing an API call on a page and I'm unsure about what's wrong with the Subscribe/Observe method. Currently, this is the code that I have: import { Component, OnInit } from '@angular/core'; import { Ro ...

Transform JSON arrays into JSON structure

I'm currently facing an issue with converting JSON arrays to JSON format data. The output I am currently getting looks like this: https://i.stack.imgur.com/SW2NW.png However, I would like my output to be in the following format: https://i.stack.img ...

What is the reason for the allowance of numeric keys in the interface extension of Record<string, ...>

I am currently working on a method to standardize typing for POST bodies and their corresponding responses with API routes in my Next.js application. To achieve this, I have created an interface that enforces the inclusion of a body type and a return type ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Modifying a chosen row within a table using Angular

Currently, I am working on developing a To-Do list application using Angular 11. The application includes a Bootstrap table where data is displayed upon clicking the add button. Each row in the table contains icons for delete, edit, save after editing, and ...

Issue with Promise not resolving in Node when using Edge

As I explore the best way to utilize my C# dlls with Edgejs for Node, I encountered a situation where one proxy function in Node appears like this (a class method in Typescript): readSettings(args: ReadSettingsParams) : Promise<response> { let $ ...

Is there a fresh method in C++11 to loop through vectors?

I recently came across two different ways of iterating through a vector. The first is: for (int i=0,num_of_roads=roads.size();i<num_of_roads;++i) { roads[i]//... } And the second way is: for (Road road:roads) { road//... } I'm curious to ...

Guide to accessing a menu through Long press or Right click in Angular2

I recently started experimenting with angular 2 and I am trying to figure out how to create a menu that opens with multiple options on both mobile and desktop devices. What I'm looking for is a way to trigger the opening of a menu when a long hold or ...

Issues with compatibility between @ngui/auto-complete and ng2-daterangepicker in Angular 16

Recently, I upgraded my Angular project from version 11 to version 16. Within the project, I am utilizing @ngui/auto-complete and ng2-daterangepicker components. However, I encountered an issue when trying to import NguiAutoCompleteModule and Daterangepick ...

Angular: Assigning a key from one variable to a value in another

I am currently facing a challenge with rendering a form on a page using ng-repeat, where the data for this form is dynamically fetched from a request. Within this data, there is a nested array called "categories" which contains IDs. I want to display the n ...

Utilizing lazy loading in Angular with 2 modules that require sharing the same service

Custom Module Integration: export class CustomModule { static forRoot(): ModuleWithProviders { return { ngModule: CustomModule, providers: [ MyService ] }; } } Dynamic Module #1: @NgModule({ imports: [ CommonM ...