find the middle element in the Vue array

Currently in the process of developing a custom Vue carousel component, I have utilized some code snippets from this resource: link

My goal right now is to enhance the slider with additional navigation bullets. However, due to the justify-content:center property, it always displays the middle item in my array.

I am attempting to calculate the active item by determining the middle item in my array using the following approach:

<script>
    export default {
        data() {
            return {
                slides: [
                    {
                      title: 'I am slide A',
                      featured: 1,
                      img: '/images/carousel-img.png',
                      id: 1
                    },
                    {
                      title: 'I am Slide B',
                      featured: 0,
                      img: '/images/carousel-img.png',
                      id: 2
                    },
                    {
                      title: 'I am Slide C',
                      featured: 0,
                      img: '/images/carousel-img.png',
                      id: 3
                    }
                ],
                activeImage: (this.slides.length / 2)
            };
        }
    }
</script>

Unfortunately, this method does not work as intended. I am stuck at this point and would appreciate any guidance on how to proceed in the right direction.

Thank you.

Answer №1

slides.length / 2 will provide a float value when the array has an odd number of items. To obtain an integer value, try:

Math.floor(slides.length / 2)`

or

~~(slides.length / 2)

You can then use this index to access an item in the array

slides[Math.floor(slides.length / 2)]

For example:

const demo = new Vue({
  el: '#demo',

  data: {
      slides: [
        {
          title: 'I am slide A',
          featured: 1,
          img: '/images/carousel-img.png',
          id: 1
        },
        {
          title: 'I am Slide B',
          featured: 0,
          img: '/images/carousel-img.png',
          id: 2
        },
        {
          title: 'I am Slide C',
          featured: 0,
          img: '/images/carousel-img.png',
          id: 3
        }
      ],
  },

  methods: {

    getActiveImage: function () {
        return Math.floor(this.$data.slides.length / 2);
    }

  }
});

// In template: <div> {{getActiveImage()}} </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

What is the process for incorporating the !important declaration into a CSS-in-JS (JSS) class attribute?

I'm currently exploring the use of CSS-in-JS classes from this specific response in conjunction with a Material UI component within my React project. In order to override the CSS set by Bootstrap, I've decided to utilize the !important modifier. ...

Styling a fixed sidebar in Vue.js

I am currently working on a layout design that includes a fixed sidebar on the left side, positioned beside a container with its own grid structure. Utilizing Vue.js means each template contains <div> elements where I attempt to incorporate additiona ...

Error: This Service Worker is restricted to secure origins only due to a DOMException

Having trouble implementing this on my website; it keeps showing the following error. Help, please! Service Worker Error DOMException: Only secure origins are allowed. if ('serviceWorker' in navigator && 'PushManager' in wind ...

What is the method for configuring environment variables in the Lumber framework?

Installing Lumber CLI npm install -g lumber-cli -s Next, lumber generate "adminpanel_test" --connection-url "mysql://root@localhost:3306/admin-dev" --ssl "false" --application-host "localhost" --application-port "3310" Error: lumber is not recognized a ...

The importance of variables in Express Routing

I'm really diving into the intricacies of Express.js routing concepts. Here's an example that I've been pondering over: const routes = require('./routes'); const user = require('./routes/user'); const app = express(); a ...

Utilize the power of REACT JS to transform a specific segment within a paragraph into a hyperlink. Take advantage of the click event on that hyperlink to execute an API request prior to

In React JSX, I'm encountering an issue trying to dynamically convert a section of text into an anchor tag. Additionally, upon clicking the anchor tag, I need to make an API call before redirecting it to the requested page. Despite my attempts, I have ...

Creating a centered and beautifully styled picture with a specific maximum size using React

I recently completed the development of a new website, which can be viewed at Upon inspection of the website, it is evident that the photo is not centered and appears too large on mobile phones. Despite my efforts to align it using various methods outline ...

Unable to retrieve the user ID from a Discord username using Discord JS

let string = `${args[1]} ${args[2]}` console.log(string) const idofuser = client.users.cache.find((u) => u.username === `${string}`).id I am facing an issue with DiscordJS where it says "cannot read property 'id' of undefined" when trying to ...

Avoid matching the regular expression

Currently, I am utilizing the regular expression /\s*?left:\s*?-?\d+\.?\d*px;/im to search for instances like: left: 100.5px;. An issue that I am encountering is that it also detects margin-left: 100px; or padding-left.... My obje ...

What is the reason for calling Proxy on nested elements?

Trying to organize Cypress methods into a helper object using getters. The idea is to use it like this: todoApp.todoPage.todoApp.main.rows.row .first().should('have.text', 'Pay electric bill'); todoApp.todoPage.todoApp.main.rows.ro ...

Is it possible to drag the div container in HTML to resize its width from both left to right and right to left?

After posing my initial inquiry, I have devised a resizing function that allows for the expansion of a div's width. When pulling the right edge of the div to resize its width from left to right, is it possible to adjust the direction or how to resize ...

What is the best way to restrict navigation for a subroute in Vue.js?

One of the great things about beforeRouteLeave is its ability to prevent navigation under specific conditions. In my setup, I utilize a subroute to display a part of the page. I am looking for a way to implement a navigation guard on the subroute to prohi ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

Having difficulty using the forEach() method to loop through the array generated by my API

During my troubleshooting process with console.log/debugger, I discovered that I am encountering an issue when attempting to iterate over the API generated array in the addListItem function's forEach method call. Interestingly, the pokemonNameList ar ...

Using Angular to Bind JSON Data

I'm currently in the process of evaluating different JS frameworks for a project and I find myself torn between Angular and Ember. As I continue to explore Angular, I have a specific question regarding data binding to an external json file stored on S ...

Issue with callback function not triggering after comment deletion in REACT

Although I am successfully able to delete the comment, I am facing an issue where the callback function is not being invoked. My suspicion is that it might be related to how I pass multiple arguments to the function, but I cannot confirm this. Below is th ...

Ways to retrieve several parameters from a controller using Ajax Jquery in Codeigniter

I need to retrieve a list of images from a folder based on a specific ID. Currently, I am able to get the file names but I also require the upload path. Is there a way to obtain both sets of data using a single function? Javascript Code: listFilesOnServ ...

What is the process of adding a div to the left side of the parent element in AngularJS

I am trying to append the code on the left side of the click. My current controller code looks like this: demo.$inject = ['$scope']; demo.directive("boxCreator", function($compile){ return{ restrict: 'A', l ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

Information within specified dates shows all leaders

Looking to filter data based on Start Date, End Date, and HeadName. The current search query successfully filters between dates but does not properly filter the HeadName column, displaying all results instead. Sno HeadName Date Amount BillNo BillD ...