Exploring the power of grouping and iterating through object/arrays using the .reduce method in Vue

Imagine having an array with unknown IDs. How can we dynamically group and display them? Since the number of different IDs is uncertain, the number of arrays created will also be unknown.

In theory, the solution could involve grouping objects by their respective IDs and pushing them into new arrays named as 'array-0', 'array-1', and so on. Then, we would need to determine the total number of arrays created and iterate through the items using something like

item in array-["n in nArrays"]
. Although this approach may not work due to limitations on dynamically creating loops, it helps illustrate the concept.

array: [
  { id: 11, item: "item" },
  { id: 49, item: "item" },
  { id: 11, item: "item" },
  { id: 20, item: "item" },
  { id: 49, item: "item" },
  { id: 83, item: "item" },
]
<div v-for="item in array-0">
  {{ item }} // all items with id 11 for instance
</div>

<div v-for="item in array-1">
  {{ item }} // all items with id 20 for example
</div>

However, the aim is to achieve dynamic functionality.

<div v-for="item in array-[n in nArrays]">
  {{ item }}
</div>

Answer №1

A reducer from this source can be utilized along with the function below:

function groupBy(objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    const curGroup = acc[key] ?? [];
    
    return { ...acc, [key]: [...curGroup, obj] };
  }, {});
}

This approach provides a neatly organized object that can be easily iterated over:

const data = [
  { id: 11, item: "first one" },
  { id: 49, item: "tasty thing" },
  { id: 11, item: "amazing right?" },
  { id: 20, item: "cool cool" },
  { id: 49, item: "love watermelons" },
  { id: 83, item: "and you?" },
]

groupBy(data, 'id')
// resulting object will look like this
{
  "11": [
    {
      "id": 11,
      "item": "first one"
    },
    {
      "id": 11,
      "item": "amazing right?"
    }
  ],
  "20": [
    {
      "id": 20,
      "item": "cool cool"
    }
  ],
  "49": [
    {
      "id": 49,
      "item": "tasty thing"
    },
    {
      "id": 49,
      "item": "love watermelons"
    }
  ],
  "83": [
    {
      "id": 83,
      "item": "and you?"
    }
  ]
}

The complete code implementation would resemble this:

<template>
  <main>
    <div v-for="(groupedData, id) in itemsToIterateOn" :key="id">
      <pre v-for="array in groupedData" :key="array.item">{{ array }}</pre>
      <hr />
    </div>
  </main>
</template>

<script>
const groupBy = (objectArray, property) => {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    const curGroup = acc[key] ?? [];

    return { ...acc, [key]: [...curGroup, obj] };
  }, {});
};

export default {
  data() {
    return {
      itemsToIterateOn: groupBy(
        [
          { id: 11, item: "first one" },
          { id: 49, item: "tasty thing" },
          { id: 11, item: "amazing right?" },
          { id: 20, item: "cool cool" },
          { id: 49, item: "love watermelons" },
          { id: 83, item: "and you?" },
        ],
       "id"
      ),
    };
  },
};
</script>

Resulting in a visual representation like this:

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

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

The input tag contains an empty Request.Form

My issue lies in using Request.Form to retrieve text from an input field, as the value always ends up being empty. My goal is to extract the text value from the input tag and use it to query my database. I have attempted to write to an ASP TextBox but enco ...

"Having trouble with sound in react-native-sound while playing audio on an Android AVD? Discover the solution to fix this

react-native-sound I attempted to manually configure react-native-sound but I am unable to hear any sound. The file was loaded successfully. The audio is playing, but the volume is not audible on Android AVD with react-native-sound. ...

Building a versatile and interactive table using AngularJS with data sourced from a

I am currently working on creating a dynamic table using Angular JS to display data received from a Spring Rest Service. Here is the code snippet I have been working with: // JavaScript Document var app = angular.module("SDLC", []); app.config([&apos ...

Issue with Ajax: parameters failing to pass without using jQuery

It appears that I am only receiving jQuery results, but I am in search of the correct method to pass parameters via AJAX without using libraries or old browser fallbacks. If there is another thread discussing this topic that I have overlooked, please provi ...

The Canvas Clear function is malfunctioning; the items in the array are not being deleted

Even after being deleted from the array, the squares are still drawn. Shouldn't they disappear when removed from the Array? Does the array not update within the go function? Javascript: var canvas; var ctx; $(document).ready(function(){ $("#t ...

Ways to emphasize search outcomes in Flask/HTML?

I am currently working on creating a search box using HTML and the Flask framework in Python. Below is the layout I am working with: Layout My goal is to input text into the search box and have it highlighted within the text area on the same HTML page. F ...

Showing Nested Arrays in Angular 2

If I have an array with image links as shown below, how can I display them in HTML? array = [ { img: [ {0: 'http://hairsalonfurniture.eu/wp-uploads/750x480_how-to-create-a-nice-hair-salon-s-reception-gjzd.jpg',}, {1: 'http ...

What is the best way to handle a specific submit button using jQuery/Ajax?

I created a web page with 4 submit buttons that all call the same PHP page process.php using jQuery/Ajax. I trigger this PHP page using the onClick event as shown below: <div class="col-md-12"> <input type="hidden" name="_token" value="<?p ...

Is it possible to stack one Canvas on top of another?

Right now, I am engaged in a process that involves: creating a canvas and attaching it to a division applying a background image through CSS to that canvas. drawing a hex grid on the canvas placing PNGs on the canvas. animating those PNGs to show "movem ...

JavaScript eliminates any existing CSS styling

I am new to the world of web development and recently created a sample webpage. The page consists of an HTML file, a CSS file, and a JavaScript file. However, I encountered an issue where linking the JavaScript file to the HTML page caused the CSS formatti ...

Is it considered a poor practice to self-instantiate within a static method of a JavaScript class

Do you think this object-oriented JavaScript (TypeScript) code is not well-written? class KYC { public reference; public data = null; constructor(id: string) { this.reference = id ? firestoreAdmin.collection('kyc').doc(id) : fi ...

Invoking a PHP function within a JavaScript file

I'm facing an issue with calling a PHP function from JavaScript. I have written a code snippet where the PHP function should print the arguments it receives, but for some reason, I am not getting any output when running this code on Google Chrome. Can ...

What are the consequences of incorporating JavaScript in PHP code for changing locations?

There is a recurring question on Stack Overflow about redirecting users in PHP after input or values have been changed, and the common suggestion is to use headers for this task. However, it's important to note that headers in PHP need to be modified ...

Click on the image to select a radio button option

Query How can I display the appropriate dropdown when clicking on the image or checkbox, while hiding the radio button in the end? I suspect it may be a scoping problem as the options are not appearing correctly even when the radio button is checked. Vie ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

Exploring the versatility of combining CSS classes with MUI 5 SX prop

Is there a way to use multiple CSS classes with the MUI 5 SX prop? I've defined a base class for my Box components and now I want to add a second class specifically for styling the text inside the Box. When I try to apply both classes like sx={styles. ...

Complete picture in a circular div with aspect ratio

I'm currently working on creating a profile page and I'd like to have an image inside a circular div. The challenge is that I want the image to maintain its aspect ratio, even though the dimensions are unknown and users can upload images of any s ...

Using Javascript, display an image that was previously hidden with CSS when a radio button is selected

Within a table of 25 rows, each row contains an attribute accompanied by an image (represented by a tick symbol) and five radio buttons for rating the attribute from 1 to 5. Upon clicking one of the radio buttons, the hidden image (tick symbol) should beco ...

How can I check if the VPN is turned off in a React application?

import React from "react"; import { Offline, Online } from "react-detect-offline"; export default function DropDown() { return ( <> <Online>Only displayed when connected to the internet</Online> <Offline ...

Assess JavaScript for Fetch API implementation

Currently, I am utilizing node.js on Windows with the express module to create an HTML page where I need to retrieve data from a server-side function called getfiledata() (I want to keep my Javascript and text file private). I have attempted to use fetch( ...