How to eliminate the comma from the final element in a JavaScript Vue.js array?

I'm looking to remove the comma from the last element in Vue, but I'm unsure how to do so since the index of the last element is unknown.

<td v-if="category.sub_category.length > 0"> 
                      <template v-for="cat in category.sub_category">
                        {{ addComma(cat.subcategory_name) }}
                      </template>
                    </td>

addComma(subCat) {
  let elements = [];
  elements.push(subCat);
  console.log(elements);
  
  if (elements != ""){
    elements += ", ";
  }

  return elements;
},

Here's the output of console.log(elements) mentioned earlier.

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

Below are the results of the code provided above.

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

Answer №1

Here's a solution that should do the trick:

<td v-if="category.sub_category.length > 0">
      {{category.sub_category.map(({subcategory_name}) => subcategory_name).join(', ')}}
</td>

Personally, I might consider moving this to a computed property for cleaner markup:

<td v-if="category.sub_category.length > 0">
      {{subcats}}
</td>


computed: {
  subcats() {
    return this.category.sub_category.map(({subcategory_name}) => subcategory_name).join(', ');
  }
}

Answer №2

Joining elements comma separated

A simple way to achieve this is by using the elements.join(',') method directly inside Vue tag like so:

{{elements.join(',')}}

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

Please refer to the provided image for more clarity. I confirmed the answer after careful consideration.

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

Extract information from a webpage using JavaScript through the R programming language

Having just started learning about web scraping in R, I've encountered an issue with websites that utilize javascript. My attempt to scrape data from a specific webpage has been unsuccessful due to the presence of javascript links blocking access to t ...

The createElement function in Vue.js does not always return a fully formed component

There is a scenario where I need to create a functional component for a specific purpose. The task at hand involves taking all the children elements and adding some additional props to them, but only to those that are custom components of type ChildCompone ...

The ng-click functionality is not functioning as expected within the directive

Take a look at this snippet of my HTML: <section ng-controller="GalleryController as gallery"> <nav footer-directive></nav> </section> This is the GalleryController I'm using: angular .module('myapp') ...

Encountering difficulties hosting create-react-app build on shared server, receiving 404 errors specifically linked to the chunk.js file

After working smoothly with create-react-app, I encountered an issue when attempting to create a build. Following the command: npm run build The build was successfully created. However, upon downloading and uploading the build file to a shared server via ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

The Bootstrap validator triggers the form submission only after the second click

When I click on the submit button, I am attempting to submit a form that has its default action prevented and first checks a condition before proceeding. Below is the code snippet: $('#payment-form').bootstrapValidator({ live: 'dis ...

Implement the use of HTML buttons to dynamically change the source attribute of an image using

I am in the process of creating a webpage with 25 different images that will be displayed one at a time. Each image represents unique combinations from two sets of items: (ant, blueberry, ladybug, marshmallow, mushroom) and (blimp, truck, moon, ocean, redw ...

Utilizing VueJS to manage URL fragments for functionality without the need for Vue Router or jQuery

I have been using VueJS 2.x but haven't delved into VueRouter just yet, as it's not feasible for me at the moment. Basically, I'm looking for a way to make Vue recognize a URL fragment like https://example.com/mypage#record-17 and then trig ...

Nuxt is throwing an error because it cannot find the definition for Stripe

I'm having trouble integrating Stripe elements into my Nuxt.js page and I keep getting an error. Error: Stripe is not defined I have added the <script src="https://js.stripe.com/v3/"></script> to my nuxt.config.js Here's my code: ...

Within Codesandbox using Vue, the error message 'The property or method "children" is not defined in the instance, but is referenced during rendering.' appeared

Currently, I am in the process of creating a versatile State Manager that can seamlessly integrate with various Frontend Frameworks, including Vue. In order to showcase how the State Manager can be utilized within Vue, I have set up a simple codesandbox de ...

Which five key JavaScript concepts should I grasp in order to excel as an AngularJS developer?

Coming from a background of server-side coding, I am delving into the world of AngularJS now. This means I need to have a solid grasp of JavaScript before diving in. If I don't have enough time to master JavaScript completely at the moment, what are ...

I am facing difficulties in adding dynamic content to my JSON file

I've encountered a challenge in appending new dynamic data to a JSON file. In my project, I receive the projectName from an input form on the /new page. My API utilizes node.js's fs module to generate a new JSON file, where I can subsequently add ...

Convert a two-column layout on the web into a single-column layout for mobile devices, featuring dynamic

Is there a way to style this diagram with CSS that will work on IE11 and all major browsers? It seems like Flexbox doesn't support dynamic height. Do I need separate left and right columns for larger viewports and no columns for smaller viewports? ...

jQuery's capability to select multiple elements simultaneously appears to be malfunctioning

I am dynamically creating div elements with unique ids and adding span elements with specific CSS properties. $(".main").append("<div class=largeBox id=" + counter + "</div>"); $(".largeBox").append("<span class=mainTitle></span>"); ...

Struggling to Load: Ajax Request to Google App Engine Causing Page to

I have developed a page that communicates with a Python application running on Google App Engine to retrieve JSON data using JSONP for cross-origin functionality. However, I am encountering an issue where the page hangs and fails to display the data no mat ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

How to implement a scrollbar for tables using Angular

How can I implement a vertical scroll bar only for the table body in my Angular code? I want the scroll bar to exclude the header rows. Since all rows are generated by ng-repeat, I am unsure how to add overflow style specifically for the table body. Here ...

AngularJS - Textarea not resetting content on ng-click event

Having an issue with my textarea. When attempting to clear it using ng-click, nothing happens... Can anyone provide assistance? Here is my code for testing: My app If you prefer to view it here: HTML : <div ng-controller="Ctrl1"> <d ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

Quicker Solution to Iteration in Google Apps Script with JavaScript

I've set up a for loop to extract sales data from an array (salesLog) and transfer it to a designated sheet (targetSheet) in columns. The sales data is spread across multiple columns in the array. The loop adds up the columns between columnStart and c ...