How can we generate 3 different arrays, each containing an equal number of items except for the last array, using VueJS?

Incorporating Bootstrap5 and VueJS 2, I am working on designing a layout of cards in a "pinterest-style" arrangement, as depicted in the following screenshot:

https://i.sstatic.net/AvdWR.png

To achieve the layout showcased above, the HTML markup required is as follows: [Access Codesandbox here]

<main>
    <div class="container-fluid">
        <div class="row">
           <div class="col-md-9">
                <div class="row">
                      <div class="col-md-4">
                        <article>
                        </article>
                        <article>
                        </article>
                      </div>
                      <div class="col-md-4">
                        <article>
                        </article>
                        <article>
                        </article>
                      </div>
                      <div class="col-md-4">
                        <article>
                        </article>
                        <article>
                        </article>
                      </div>
           </div>
        <aside class="col-md-3 ml-auto">
           ...sidebar content...
        </aside>
        </div>
    </div>
</main>

What JavaScript technique can I utilize to split a data array into 3 new arrays with equal elements in each, except for the last array? This would enable me to structure the layout as per the screenshot displayed above. For instance, if the initial data array is [1,2,3,4,5,6,7,8,9,10,11], I aim to obtain something like

[ [1,2,3,4], [5,6,7,8], [9,10,11] ]

Although I made an attempt at this in VueJS, it appears my approach was flawed as some cards had gaps and the order was incorrect. My knowledge of JavaScript may be limited. My attempt: https://codesandbox.io/s/vue-bootstrap-card-layout-0xjlt?file=/src/App.vue

Answer №1

You were almost there, but in order to determine the exact number of chunks, you need to divide the number of items by the desired number of columns and round up to the nearest whole number...

Math.ceil(this.mockData.length / 3)
  computed: {
    chunkArray() {
      let result = [];
      const size = Math.ceil(this.mockData.length / 3);
      for (let i = 0; i < this.mockData.length; i += size) {
        let chunk = this.mockData.slice(i, i + size);
        result.push(chunk);
      }
      return result;
    },
  },

Check out the Codesandbox for more information

Answer №2

If you prefer the order to be arranged in a "horizontal" manner like this:

[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9]]

Then a slightly different strategy needs to be employed. You can iterate through the items and assign them to the appropriate sub-array (similar to distributing a deck of cards to three players).

computed: {
  chunkArray() {
    let result = [];
    const cols = 3;
    this.mockData.forEach((item, index) => {
      let i = index;
      // find the index of the target sub-array 
      while (i >= cols) {
        i -= cols; // i will be 0, 1, or 2
      }
      // create the sub-array if it doesn't exist
      if (!Array.isArray(result[i])) {
        result[i] = [];
      }
      // add the item to the sub-array
      result[i].push(item);
    })

    return result;
  },
},

https://codesandbox.io/s/vue-bootstrap-card-layout-forked-cj0w1?file=/src/App.vue:7492-7847

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

Troubleshooting the issue of post-initialization store updates not functioning in AlpineJS

When setting up a store, I initially use: document.addEventListener('alpine:init', () => { Alpine.store('selectedInput', 0) }) However, when attempting to update selectedInput within a function later on, it doesn't reflect th ...

Encountering a 404 error while accessing my meticulously crafted express server

After ensuring that the server is correctly set up and without any errors related to imports or missing libraries, I utilized cors for development purposes. A 404 error persisted even after attempting to comment out the bodyparser. https://i.stack.imgur.c ...

Is it possible to resend an AJAX request using a hyperlink?

Is it possible to refresh only the AJAX request and update the content fetched from an external site in the code provided below? $(document).ready(function () { var mySearch = $('input#id_search').quicksearch('#content table', ...

Delay the axios get request in the useEffect

Working with React JS, I have implemented a useEffect hook to request data from a database via an Express server when the page renders. However, if the server is down, the app will continue to make thousands of requests until it crashes. Is there a way to ...

Tips for sending variable from JavaScript to PHP Page through XMLHTTP

Make sure to review the description before flagging it as a duplicate. In my understanding, the method of transmitting data from JavaScript to PHP is through Ajax Call. This is the situation I am facing: With PHP, I bring forth an HTML page that cont ...

The browser displays the jQuery ajax response instead of passing it to the designated callback function

I have a web application that connects to another web service and completes certain tasks for users. Using codeigniter and jQuery, I have organized a controller in codeigniter dedicated to managing ajax requests. The controller executes necessary actions ...

Looking for the function to activate when the enter key is pressed

I have a search box which is a text type and has a click button that initiates the Find() function. How can I enable searching by pressing Enter inside the textbox? ...

Tips for obtaining a specific sorting order based on a wildcard property name

Here's the structure of my JSON object, and I need to sort it based on properties starting with sort_ { "sort_11832": "1", "productsId": [ "11832", "160", "180" ], "sort_160": "0", "sort_180": " ...

Guide on sending a JSONP POST request using jQuery and setting the contentType

I'm struggling to figure out how to make a jsonp POST request with the correct content type of 'application/json'. Initially, I was able to send the POST request to the server using the jQuery.ajax method: jQuery.ajax({ type: ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...

Changing ch to Px in CSS

Important Notes: I have exhaustively explored all the questions and answers related to this particular topic. The question I have is very straightforward: How many pixels are equivalent to 1 character? Here's a sample of my code - code Related Sear ...

Attempting to call a nested div class in JavaScript, but experiencing issues with the updated code when implemented in

Seeking assistance. In the process of creating a nested div inside body > div > div . You can find more information in this Stack Overflow thread. Check out my JSFiddle demo here: https://jsfiddle.net/41w8gjec/6/. You can also view the nested div ...

What is the best way to access a particular property of an object?

Currently, I am successfully sending data to Mongo and storing user input information in the backend. In the console, an interceptor message confirms that the data is received from MongoDB. However, I am struggling to extract specific properties such as th ...

Exporting data acquired from a MongoDB query using Node.js

I am currently working on exporting the contents of a MongoDB collection by using exports.getAllQuestions = async function (){ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("Time4Trivia"); ...

Getting input elements with Puppeteer can be done by waiting for the page to fully load all elements within the frameset tag

Seeking to gather all input elements on this website: This is how the element source page appears. Below is my code snippet: const puppeteer = require("puppeteer"); function run() { return new Promise(async (resolve, reject) => { try { ...

The unique capabilities of services and factories in Angular 1 - understanding their differences and what each excels at

After extensively combing through numerous stackoverflow posts and articles, the consensus seems to be that an angular service returns an instance, while an angular factory returns any desired object. This raises the question: what unique capabilities do ...

What is causing ngResource to change the saved object to something like "g {0: "O", 1: "K", ..} once it receives a response?

In my current setup, I have a default ngResource that is defined in the following way: var Posts = $resource('/posts/'); Once I retrieve a blog post from my nodejs server using the code below: $scope.post = Posts.get({_id:query._id}); The use ...

Communication through HTTP requests is not supported between docker containers

I currently have two applications running as services within a docker-compose environment. My React App A Node.js server In an attempt to make an HTTP request from my React app to the Node.js server, I am using: fetch("http://backend:4000/") However, w ...

New Angular Datatables used to create a revitalizing table

In my project, I am utilizing the Angular Datatables library. The data is fetched from a URL that returns a JSON object, which is then stored in an array and used to populate a table. appenditems(){ this.items = []; this.items2 = []; this.items ...

Tips on retrieving PHP variable values along with HTML response using AJAX in PHP

I am looking to retrieve 2 variables: 1) The total number of records from the mysqli query performed in search_members.php 2) A boolean value indicating whether any results were found Below is the code I have written: <input type="button" value="Sea ...