For every group of 5 rows in the table, iterate through

Is it possible to create a new row in a table every time the 5th <td> element is reached?

For example, if we have the following data set: [1,2,3,4,5,6];

We can use the following component:

<tr v-for="(item,index) in data">
   <td v-if="(index + 1) % 5 !== 0">{{item}}</td>
</tr>

The expected outcome would be:

| 1 | 2 | 3 | 4 | 5 |

| 6 |

Answer №1

Check out this simple and clear solution that utilizes the reduce method:

new Vue({
  el: '#root',
  data: {
    numbers: [1, 2, 3, 4, 5, 6, 7]
  },
  computed: {
    chunkedNumbers: function() {
      return this.numbers.reduce((result, item, index) => { 
        const chunkIndex = Math.floor(index/5)

        if(!result[chunkIndex]) {
          result[chunkIndex] = [] // start a new chunk
        }
        result[chunkIndex].push(item)

        return result;
      }, []);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<table id="root" style="border: 1px solid black">
  <tr v-for="row in chunkedNumbers">
    <td v-for="column in row" style="border: 1px solid black">{{column}}</td>
  </tr>
</table>

Answer №2

You have the option to utilize a computed property that will divide the array into sections of 5 items each. Afterward, you can iterate through the 2D array and generate rows and columns accordingly.

new Vue({
  el: '#example',
  data: {
    array: [1, 2, 3, 4, 5, 6]
  },
  computed: {
    grouped: function() {
      const n = 5; // size of each chunk
      const length = Math.ceil(this.array.length / n);
      return Array.from({ length }, (_, i) => this.array.slice(i * n, (i + 1) * n))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<table id="example">
  <tr v-for="row in grouped">
    <td v-for="column in row">{{column}}</td>
  </tr>
</table>

Reference for Chunking Code

Answer №3

If you want to create a 2D array based on a specific chunk size, you can achieve this by using the splice method within a while loop.

Check out this Code Snippet for guidance:

new Vue({
  el: '#example',
  data: {
    array: [1, 2, 3, 4, 5, 6]
  },
  computed: {
    lists: function() {
      const n = 5, // chunk size
        twoDArray = [],
        data = this.array;

      while (data.length) {
        twoDArray.push(data.splice(0, n));
      }
      return twoDArray;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<table id="example">
  <tr v-for="row in lists">
    <td v-for="column in row">{{column}}</td>
  </tr>
</table>

Answer №4

When working with Vue JS loops, the second parameter represents the index of each item in the loop.

<tr v-for="(item,index) in data">
  <td v-if="(index % 5 == 0)">{{item}}</td>
</tr>

This index can be used to apply conditions within the loop. For instance, you can use modulo operation to check if the index is a multiple of 5.

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

Steps to calculate the total number of rows in a datatable

I have implemented a datatable in my project, and I need to find out the total number of rows in the table when it is loaded. Here's the snippet of code I am currently using: $(document).ready( function() { $('#jobSearchResultTable').data ...

Tips on changing tabs by simply clicking the save button or linking the save button to tab-switching functionality

import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms'; import { CustomValidators } from 'ng2-validation'; import { Busi ...

In VueJS, ensure that any updates to the data in the parent component are seamlessly passed on to its child components

Is there a way to pass down updates in data values from a parent component to its child components whenever the parent's value changes in Vue.js? I have 3 custom components that need to display the most up-to-date value of the parent component. By the ...

Exploring the Power of Integrating SignalR 2 with a Database

After going through a tutorial on creating a basic messaging web application using SignalR and MVC, I realized that the tutorial did not cover how to store messages in a database or display previous messages to users. The main code snippet from the tutoria ...

Tips for saving JSON data in a file with writeFileSync

I'm currently working on a project related to home automation using IoT technology. In this project, my websocket server acts as a subscriber to a MQTT broker, receiving temperature and light intensity data from a microcontroller in the form of JSON d ...

What is the best way to showcase all tab content within a single tab menu labeled "ALL"?

I have created a tab menu example below. When you click on the button ALL, it will display all the tabcontent. Each tab content has its own tab menu. Thanks in advance! function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = doc ...

The React application is failing to build and is displaying the error code ELIFECYCLE

Having trouble with this error that keeps popping up every time I attempt to build the project. Can anyone provide assistance? Error code ELIFECYCLE Error number 1 Error in [email protected] build: react-scripts build Exit status 1 Failed at the [ema ...

When using Next.js revalidate, an error may occur stating: "There are keys that require relocation: revalidate

I have been attempting to utilize the revalidate function in my code by following the example provided by Vercel. However, I keep encountering an error. Here is the snippet of code that I am currently using: export async function getServerSideProps() { c ...

Executing a function stored in an array using JavaScript

While practicing JavaScript, I came across a sample code where I tried to call a function from an array. However, the output returned undefined along with the expected result from the function. I'm confused as to why this is happening, especially sinc ...

Issue with updating md-slider value using ng-model when md-discrete directive is applied

var app = angular.module('StarterApp', ['ngMaterial']); .overflow-hidden{ overflow: hidden; } md-slider:not(.active) .md-thumb-container{ transition: tr ...

What is the process of sending Firebase topic notifications through Node.js and Express?

As an Android developer, I am trying to send notifications to all users in my app who are subscribed to the topic named ALL_USER. However, I have encountered difficulties in sending notifications to that specific topic. Thank you in advance for your assis ...

conceal a division beneath a YouTube video frame upon clicking

I need to hide the 'div .blind' element when a YouTube video (inside 'div #player') is clicked. How can I achieve this? Here's an example: JS: ... var player; function onYouTubeIframeAPIReady() { player = new YT.Player('pl ...

Exclude mock files from webpack configuration in AngularClass/angular2-webpack-starter for production builds

I've encountered some obstacles while working with the AngularClass/angular2-webpack-starter framework, specifically in configuring its webpack settings. My goal is straightforward, yet I've been struggling to achieve it. In my project directory ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

Using Django to highlight a table row when a user is detected

I have two entity classes named participant and holder that share the fields: first_name, last_name, and date_of_birth In the detail view of the participant Model, I compare these fields with those in the holder model: for holder in Holder.objects.all(): ...

Changing the URL parameters to accommodate a specific query

Currently, I have set up the route as follows: app.get("/employees", (req, res) => { data.getAllEmployees().then((data) => { res.json(data); }).catch(function(err) { console.log("An error was encountered: " + err); }); }) ...

Tips for meeting a JavaScript door unlocking condition with an HTML button

In this tutorial, the https://www.w3schools.com/nodejs/nodejs_raspberrypi_webserver_websocket.asp link demonstrates an event handler that works based on an HTML checkbox. I am interested in achieving a similar functionality, but with a button instead, to t ...

Why does el-select display options in a horizontal manner?

I have recently made the switch from vue.js to vue3 and migrated from using element-ui to element-plus. However, I have encountered a strange issue with the el-select component. The options are being displayed horizontally, like a wrappanel, rather than in ...

Arranging Columns in Angular

Here is the code I'm struggling with, as I can't seem to make it work. I don't see any issues with it, but still: In my app.component.html file, I have: <table border="1"> <!-- ADD HEADERS --> <tr> ...

Activated a DOM element that was retrieved through an AJAX request and displayed it inside a light

I want to implement a lightbox plugin (specifically lightbox_me) to display a html DOM element retrieved through an ajax request. This is the code I am using: <script src="script/jquery.lightbox_me.js"></script> <script> $(& ...