What is the best way to find the actual position of this user within my array?

I found this example in the Vue JS documentation here

When using a filtered v-for, how can I obtain the actual index of a user in the array, rather than the index of the current iteration?

<div id="filter-by-example">
  <ul>
    <li v-for="user in users | filterBy 'Jim' in 'name'">
      {{ user.name }}
      {{ $index }} <!--I want Jim's index to be 3, not 0-->
    </li>
  </ul>
</div>

Here is the Vue JS code snippet:

new Vue({
  el: '#filter-by-example',
  data: {
    users: [
      { name: 'Bruce' },
      { name: 'Chuck' },
      { name: 'Jackie' },
      { name: 'Jim' },
    ]
  }
})

Answer №1

Here is a solution that should work:

new Vue({
  el: '#filter-by-example',
  data: {
    users: [
      { name: 'Bruce' },
      { name: 'Chuck' },
      { name: 'Jackie' },
      { name: 'Jim' },
    ]
  },
  methods : {
    getIndexOfItem: function(arr, item) {
      return arr.indexOf(item);
}
  }
});
<script src="https://unpkg.com/vue@next/dist/vue.js"></script>

<div id="filter-by-example">
  <ul>
    <li v-for="user in users">
        {{getIndexOfItem(users, user)}} - {{user.name}}
    </li>
  </ul>
</div>

A method called getIndexOfItem was added to the methods collection, which takes an array and an item as parameters and returns the index of the item in the array. This approach might seem complex, but it worked when other implementations failed.

Edit 2

The function inside the methods collection has been removed.

<li v-for="(user, index) in users | filterBy 'Jim' in 'name'">

https://jsbin.com/misagagewo/edit?output

Answer №2

Unfortunately, it seems like you can't accomplish that. However, there is a workaround that you could try.

<div id="filter-by-example">
  <ul>
    <li v-for="user in users | filterBy 'Jim' in 'name'">
      {{ user.name }}
      {{ user._index }} 
    </li>
  </ul>
</div>  

In JavaScript:

function updateObjectArray(array) {
  array.forEach((elem, index) => elem._index = index);
  return array;
}

new Vue({
  el: '#filter-by-example',
  data: {
    users: updateObjectArray( [
      { name: 'Bruce' },
      { name: 'Chuck' },
      { name: 'Jackie' },
      { name: 'Jim' },
    ] )
  }
})

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

Top method for showcasing only unique values from various div tags with identical class names

Is there a way to show only unique values from multiple divs with the same class name? <div class="categories">cat 1</div> <div class="categories">cat 1</div> <div class="categories">cat 2</div> <div class="categorie ...

Showcasing a JSON file in the interface using $http in AngularJS

I am a beginner in angularjs (and programming). I am attempting to showcase a json file on my view (home.html) using $http and ngRepeat, but unfortunately, it is not working as expected. Upon inspecting the angular responses, I noticed that there are numer ...

How can I position a div in the center of a fullpage.js slide?

I'm currently utilizing the fullPage.js plugin sourced from this link: . I have successfully implemented vertical slides by using the following HTML code: <div class="section" id="section2"> <div class="slide" id="slide1"> ...

Challenges arise when attempting to pass array data from Ajax to Google Maps

I'm facing an issue with my Google map. I have a data array that is dynamically returned, and I want to use it to add markers to the map. However, the markers don't work when I pass the data variable to the add_markers() function. It only works i ...

Issue encountered: Unable to locate the file "SignInScreen" within the directory "./src/screens/authScreens" as referenced in the file "App.js"

App.js: import { StyleSheet, Text, View, StatusBar } from "react-native"; import { colors, parameters } from "./src/global/styles"; import SignInScreen from "./src/screens/authScreens/SignInScreen"; export default function A ...

Navigating through route parameters and application logic

There is an endpoint / which may receive different get parameters for oAuth and logging in to an app. A function called queryAction has been created to handle these requests. Platforms like express can route at the path level but not the res.query level, ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

Understanding the fundamentals of parseInt() and radix conceptsORExploring

Could you clarify the concept of radix in relation to parseInt()? I'm struggling to grasp how the string argument varies with different bases/radix. ...

Display the footer once the user has reached the end of the page by scrolling

Below is the footer code I am working with. <div class="row"> <div class="col-md-12"> <div> this section always remains at the bottom </div> </div> <div class="col-md-12"> <div> only v ...

merging JavaScript objects with complex conditions

I am attempting to combine data from two http requests into a single object based on specific conditions. Take a look at the following objects: vehicles: [ { vId: 1, color: 'green', passengers: [ { name: 'Joe', ag ...

React Bootstrap always displays tooltips

I have integrated react-bootstrap into my project. I am currently attempting to keep a tooltip always displayed, but I am facing some challenges in achieving this. Below are the approaches I have tried so far: <Card style={{width: '10rem'}} ...

Is it possible for a user to modify the JavaScript code on a website?

As I develop a website that heavily relies on JavaScript, I am curious about the possibility of users being able to edit the JS code themselves. For instance, if I have an ajax function that calls a.php, could a user modify the function using Firebug or a ...

Obtaining data via a URL and then displaying it in HTML with node.js and express.js

I am currently working on a JavaScript file where I am utilizing Node's 'request' module to make API calls, process data, and return an HTML response to the user. If you're interested, you can take a look at this snippet from my file. ...

Displaying Bootstrap alert after a successful jQuery AJAX call

I have been attempting to display an alert on a form once the submission action is completed. Here is my JavaScript function: function submitForm(){ // Initialize Variables With Form Content var nomeCompleto = $("#nomeCompleto").val(); v ...

Python's dynamic numpy arrays deliver flexibility and efficiency

I am attempting to create a numpy array (let's call it A) with a shape of (a, b, 1, d) where the value of d is unknown and varies depending on the input I receive. Additionally, I have another array (which we'll refer to as B) with the shape (a, ...

Determining the length and angle of a shadow using X and Y coordinates

I'm currently tackling the task of extracting data from a file generated by a software program that has the ability to add a shadow effect to text. The user interface allows you to specify an angle, length, and radius for this shadow. https://i.stack ...

Having trouble terminating the session with the authentication provider SSO on Node JS

I'm struggling with ending the session properly when a user makes a request to my /logout endpoint. I want to clear the session and require the user to log in again via SSO. Currently, after an initial login, I remain logged in without needing to re-e ...

What are the best ways to incorporate a theme into your ReactJS project?

Looking to create a context for applying dark or light themes in repositories without the need for any manual theme change buttons. The goal is to simply set the theme and leave it as is. Currently, I have a context setup like this: import { createContext ...

Adjust alterations in a Vue Component to apply to separate routes

I have a Filter tab component that I use in various routes. When I click on a tab, it becomes active. After clicking on one tab, I want it to remain active in other routes as well. How can I achieve this? Any suggestions or articles would be greatly apprec ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...