How can you implement a v-if directive in a Vue loop based on the maximum numerical value?

I am trying to display an element specifically for the cat with the most kittens, which in this scenario would be Bob:

{
  "cats": [
    {"name": "Tom",
      "kittens": [
        {"name": "Dan"}
      ]
    }
    {
      "name": "Bob",
      "kittens": [
        {"name": "Lil"},
        {"name": "Sue"},
        {"name": "Alf"}
      ]
    }
  }

Ultimately, I want it to look something like this:

<li v-for="cat in cats" :key="cat.name">
  {{ cat.name }}
  <span v-if="cat.kittens.length === biggestNumber">Top parent</span>
</li>

Any tips on how to retrieve, compare and utilize the highest length of the kittens array?

Answer №1

To obtain the indexes with the highest lengths of the arrays containing "kittens", you can utilize the computed property:

new Vue({
  el: "#app",
  data() {
    return {
      cats: [
        {"name": "Tom", "kittens": [{"name": "Dan"}]},
        {"name": "Bob", "kittens": [{"name": "Lil"}, {"name": "Sue"}, {"name": "Alf"}]},
        {"name": "Kitty", "kittens": [{"name": "Lil"}, {"name": "Sue"}, {"name": "Alf"}]},
        {"name": "Ketty", "kittens": [{"name": "Lil"}]}
      ],
    }
  },
  computed: {
    biggestNumber: function() {
      return this.maxIndices(this.cats.map(a => a.kittens.length));
    }
  },
  methods: {
    maxIndices(arr) {
      let maxLength = Math.max(...arr)
      return arr.reduce((m, c, i) => c === maxLength ? m.concat(i) : m,[]);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<li v-for="(cat, i) in cats" :key="cat.name">
  {{ cat.name }}
  <span v-if="biggestNumber.includes(i)">Top parent</span>
</li>
</div>

Answer №2

Although utilizing a computed property is the preferred approach, I find that @Nikola's response appears to be overly elaborate.

In my opinion, the inclusion of the maxIndices method seems unnecessary in this scenario.

new Vue({
  el: "#app",
  data() {
    return {
      cats: [
        {"name": "Tom", "kittens": [{"name": "Dan"}]},
        {"name": "Bob", "kittens": [{"name": "Lil"}, {"name": "Sue"}, {"name": "Alf"}]},
        {"name": "Kitty", "kittens": [{"name": "Lil"}, {"name": "Sue"}, {"name": "Alf"}]},
        {"name": "Ketty", "kittens": [{"name": "Lil"}]}
      ],
    }
  },
  computed: {
    mostKittens() {
      return Math.max(...this.cats.map(({ kittens }) => kittens.length));
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d3d0c0e5978b938b94">[email protected]</a>"></script>
<div id="app">
  <li v-for="cat in cats" :key="cat.name">
    {{ cat.name }}
    <span v-if="cat.kittens.length === mostKittens">[Top Parent]</span>
  </li>
</div>

Both the above solution and Nikola's answer have a minor flaw. They may both encounter issues if any of your cats lack a `kittens` property.

If you are absolutely certain that such a case will never occur in your component, then the precautions may not be necessary. However, in my view, it's always beneficial to safeguard against potential data inconsistencies. Here’s how I would adjust the code to account for cats without kittens:

new Vue({
  el: "#app",
  data() {
    return {
      cats: [
        {"name": "Tom", "kittens": [{"name": "Dan"}]},
        {"name": "Bob", "kittens": [{"name": "Lil"}, {"name": "Sue"}, {"name": "Alf"}]},
        {"name": "Kitty", "kittens": [{"name": "Lil"}, {"name": "Sue"}, {"name": "Alf"}]},
        {"name": "Ketty", "kittens": [{"name": "Lil"}]},
        {"name": "Stray Cat"}
      ],
    }
  },
  computed: {
    mostKittens() {
      return Math.max(
        ...this.cats.map(({ kittens }) => kittens?.length || 0)
      );
    }
  },
  methods: {
    isTopParent(cat) {
      return cat.kittens?.length === this.mostKittens;
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfa9aaba9fedf1e9f1eb">[email protected]</a>"></script>
<div id="app">
  <li v-for="cat in cats" :key="cat.name">
    {{ cat.name }}
    <span v-if="isTopParent(cat)">[Top Parent]</span>
  </li>
</div>

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

Creating an image gallery with animated effects: A step-by-step guide

I am looking to develop a creative image gallery with animated effects. I also want to include panels and hyperlinks for each image, similar to the functionality on this website: http://www.microsoft.com/en-lk/default.aspx Can anyone guide me on how to ac ...

Instructions for correctly setting up the test-ai-classifier plugin with appium for selecting UI elements

Encountered an issue on Ubuntu 20.04. Referenced the steps provided at https://github.com/testdotai/appium-classifier-plugin Installed test-ai-classifier both under the appium path and globally using npm install -g test-ai-classifier Ensured no errors f ...

How can I use Bootstrap to toggle the visibility of one dropdown menu based on the selection made in another dropdown menu?

I tried using the toggle technique, but it didn't meet my expectations. <div class="btn-group col-sm-2 col-md-2 col-lg-2"> <label>Patient Type</label> <button class="form-control btn btn-primary dropdown-toggle" data-tog ...

When performing an Angular HTTP post, additional parameters are automatically included in the request

Within a directive, I have the following code block: scope.progressCourse = -> req_data = course_id: scope.course.id success: true $http.post( "<%= Rails.application.routes.url_helpers.progress_course_path %>", req_data ).t ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

Finding the total amount in VueJS2

I'm having trouble calculating the total row in Vuejs2 as shown in the image below: https://i.sstatic.net/MLd4W.png This is the code I have been using: <tr v-for="(product, index) in form.items" :key="index"> <td class="saleTable-- ...

Converting a variable to a string in PHP

I need assistance in converting a JSON object such as [{"text":"hallo"},{"text":"hello"}] into a string that appears as "hallo hello". Currently, I am decoding the JSON object using json_decode($words, true); The decoded result is then passed to a functi ...

Determining the number of words in every line within a textarea

I am looking to determine the number of words per line in a textarea. The width of the textarea is variable. Check out this code snippet that calculates the number of rows: http://jsfiddle.net/2tcygj9e/ ...

Serialization in Jackson JSON format

Working with Jackson 2.4, I am in need of generating data to be processed by d3.js. d3.js requires my JSON values to be formatted like this : values : [[0, 13.5],[1, 2.5],[2, 5],[3, 41.2]] Within my Java model, I have the following structure : public c ...

Generating elevation graph from a kml file with the combination of php and javascript

Currently, I am exploring the Google Elevation Service with the goal of creating an elevation profile similar to the one showcased in this example: Below is the JavaScript code snippet used: var elevator; var map; var chart; var infowindow = new google.m ...

Scheduled tasks on Google Cloud Platform's App Engine are failing to run over the weekend

I am facing an issue with running a cron job in my node/express application using the node-cron library. The application is hosted on Google Cloud App Engine. My aim is to automate sending emails every day at 9 AM, but the cron seems to only work from Mon ...

Transmit JSON information to PHP and leverage it for interactions with MySQL database

I am trying to copy all selected rows from the FIRST table and insert them into the SECOND table. In JSON, I am sending the event type (insert or delete) and an array of IDs for the rows to copy. How can I access this JSON data in a PHP file? JS: var da ...

Is it possible to implement Socket.io in a node.js application without using Express at all?

I'm a beginner trying to set up a node.js server with socket.io, but I find the express package syntax confusing. My plan is to master node.js with just http, js, and socket.io first before tackling express and app.js. I've searched online for ho ...

What is the best way to calculate the average price?

Looking for help to calculate the average price of products with the available option "no" in a 2D array. Can anyone assist with this? public class Test { public static void main(String[] args) { double total = 0; Products[][] names = ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

Methods for easily accessing and manipulating arrays

Hey there, I have created an array that is giving me a lot of headaches. Could someone provide a simple solution for working with this array more efficiently? The main issue I am facing is the array offset error whenever I try to add values to it. Here i ...

Extracting data from a JSON string within a TXT document

I am looking to allow the user to select a file that will be read and parsed into JSON for storage in their localStorage. However, when reading from the file, each character is interpreted as a key, unlike when directly pasting the JSON string into the fun ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

Fetching icon using JavaScript from local file

Looking for help with a web form that allows users to upload files? I'm trying to find a way to access and extract the associated icon file from the user's system in order to include it along with the uploaded file. Any suggestions on how this ca ...

Load the entire AngularJS webpage using AJAX requests

I'm facing a challenge where I need to integrate an entire legacy page, along with some AngularJS elements, into our new page using AJAX. Initially, all I could see was the raw AngularJS markup: Rank ID {{$index+1}} {{player.playerid}} Afte ...