2

How do I display the data in the table that create a new row every 5th <td>?

example

data: [1,2,3,4,5,6];

component:

<tr v-for="item in data">
   <td>{{item}}</td>
<tr>

expected:

| 1 | 2 | 3 | 4 | 5 |

| 6 |

Kenneth
  • 2,813
  • 3
  • 22
  • 46
  • You could try to convert 1d array to 2d array, then things will be simpler. For example when it's `[[1,2,3,4,5],[6]]` easy to use as matrix – nerding_it Nov 27 '19 at 07:50

4 Answers4

2

Here's a easy to understand solution using reduce:

new Vue({
  el: '#root',
  data: {
    origin: [1, 2, 3, 4, 5, 6, 7]
  },
  computed: {
    chunkedOrigin: function() {
      return this.origin.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 chunkedOrigin">
    <td v-for="column in row" style="border: 1px solid black">{{column}}</td>
  </tr>
</table>
wuarmin
  • 3,274
  • 3
  • 18
  • 31
2

You could create a computed property to group the array into chunks of 5 items. Then loop through 2D array and create rows and columns

new Vue({
  el: '#example',
  data: {
    array: [1, 2, 3, 4, 5, 6]
  },
  computed: {
    grouped: function() {
      const n = 5; // chunk size
      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>

Chunk code reference

adiga
  • 34,372
  • 9
  • 61
  • 83
0

You could use splice method in while loop based on you chunk size you can convert into the 2-d array.

Code Snippet

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

      while (data.length) {
        gdata.push(data.splice(0, n));
      }
      return gdata;
    }
  }
})
<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>
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
-2

In vue JS loop there is a second parameter that represent the index.

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

So you could use this index to apply a condition on it. For example using the modulo to verify if the index is a multiple of 5

RomainV
  • 293
  • 4
  • 16