Having trouble with finding the correct object in an array of objects using indexOf and splice()?

Here is an example of an array of objects:

"followers": [
        {
            "id": "1be87842-2f7f-4e3b-8fde-9a998feb3a01",
            "bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece",
            "user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda",
            "username": "texample1",
            "name": "Test Example1",
            "created_at": "2018-11-27 21:01:42",
            "updated_at": "2018-11-27 21:01:42",
            "deleted_at": null
        },
        {
            "id": "7bd1fa5f-4109-4beb-b53a-fb03a1d23536",
            "bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece",
            "user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda",
            "username": "texample1",
            "name": "Test Example2",
            "created_at": "2018-11-27 21:01:48",
            "updated_at": "2018-11-27 21:01:48",
            "deleted_at": null
        }
    ]

In my vuex store, I have code that attempts to remove an object by its index from the above array:

  let followersArray = state.bugs.find(b => b.id === follower.bug_id).followers
  let index = followersArray.indexOf(follower)
  followersArray.splice(index, 1)

When passing a follower object to this mutation function, it finds the followers array in a bug object, locates the index of the follower, and attempts to remove it. However, the index logged is -1 instead of 1. Any idea what may be causing this issue? If I had the correct index, I would include a condition like if(index !== -1).

Answer ā„–1

You can utilize the findIndex() method to locate and return the index of a specific follower based on their id:

      let index = followersArray.findIndex(i => i.id === follower.id);

For instance :

let items = [{
  name: "aaa"
}, {
  name: "bbb"
}, {
  name: "ccc"
}];
let c = {
  name: "ccc"
};
let index = items.findIndex(item => item.name === c.name)

console.log(index)

Answer ā„–2

Upon executing this code and encountering a -1:

let position = followersArray.indexOf(follower);

this indicates that the follower object is not present within the followersArray. It's probable that the followersArray holds a replica of the follower object rather than a direct reference to it.

Even if the follower object shares identical attributes and values with the object at followersArray[1], the indexOf function will yield a -1 unless they are indeed the exact same object.

If your aim is simply to locate an object in the array based on a specific attribute value (like id), you could utilize map or findIndex for this purpose:

let index = followersArray.map(i => i.id).indexOf(follower.id);

Answer ā„–3

What will be displayed in the console if you print out the followersArray result? If my understanding is accurate, the find method will return an array, even when it contains only one element. Give it a try by using the following code snippet:

let followersArray = state.bugs.find(b => b.id === follower.bug_id).followers[0]

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

Searching patterns in Javascript code using regular expressions

I am dealing with two strings that contain image URLs: http://dfdkdlkdkldkldkldl.jpg (it is image src which starts with http and ends with an image) http://fflffllkfl Now I want to replace the "http://" with some text only on those URLs that are images. ...

What is the best way to update my component when the selected value is changed?

Currently, I am facing an issue with my map component. It plots polyline data based on the option selected from the select menu component. The problem arises when I change the value in the select menu and click the play button for the animation. Instead of ...

Clicking on the mail icon will open the mail with the associated mail id

When the mail icon is clicked, the mail will open with this email address. I am currently working on a project where clicking the mail icon will redirect to the mail signup page with the corresponding email address. In the image below, the red border ind ...

Utilizing async/await as a module function: A comprehensive guide

Express Route: const express=require('express'); const router=express.Router(); const trackRepo=require('../model/track'); router.post('/live',function(req,res){ const time=1439832167; const list=trackRepo.getAlerts ...

Choose all div elements except for those contained within a certain div

Having trouble with an IE7 z-index fixer that's affecting specific elements. I'm attempting to select all divs, excluding those nested within a particular div. Below is the jQuery code I'm using, but it's not functioning correctly: & ...

Modify an element upon clicking the mouse on an image

I am looking to dynamically change the paragraph element with className="details" to an editable input field when a user clicks on the image with className="edit-icon" within the same grid container. How can I achieve this functionality ...

jasmine and protractor test failing due to use of byID

My HTML markup is all set and valid. While using WebStorm to debug my test cases, I am able to view this specific element without any issues... <a id="privacyPolicy1234" on-tap="goPrivacyPolicy()" class="disable-user-behavior">Privacy Policy</a&g ...

Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected. Below is the service code: CreateItemController = $controller('Cre ...

Could the absence of a tree view in the div be due to an error in the positioning of the DOM

I'm currently working on displaying a tree structure with specific child elements inside a div using JavaScript and HTML. Despite creating all the necessary objects and ensuring that the data is correctly read from the JSON file (refer to the "data" i ...

Retrieving Values from Array with AngularJS Keys - A How-To Guide

I need to access a specific value from a key inside an array, like this: $scope.result = [ { "key":"logo_big", "value":"/assets/images/aaa.jpg" }, { "key":"logo_small", "value":"/assets/images/logo94x57Bis.png" }, { ...

Checking React props using Jest and Enzyme - A simple guide

Trying to understand React testing, I came across two files: Button.js and Button.test.js The code below contains the question along with comments: // Button.js import React from 'react'; import { string, bool, func } from 'prop-types&apos ...

Receive the outcome once the form is submitted

Can someone provide quick assistance? I am looking to allow users to upload a CSV file for me to parse and analyze. Once the processing is done, I need to display the results back to the users. While uploading the file, I also need to ensure that the file ...

Implement Babel with node.js 6.9

It puzzles me why some folks opt to use Babel for their Node.js projects. I personally utilize node 6.9 and have no issues writing ES6 code - from default arguments in functions to arrow functions, rest parameters, and spread syntax. Do you think Babel is ...

Encountering an issue where an error message indicates that a variable previously declared is now undefined

Currently, I am working on developing a small test application to enhance my coding skills. However, I have encountered a roadblock while attempting to display dummy information from a mongodb database that I have set up. I have tried various solutions bu ...

Unable to display search results with AJAX in Select2

I'm struggling with getting the desired outcomes to display in Select2 when using AJAX. Below is my code: $(document).ready(function() { $("#producto").select2({ placeholder: 'Select a product', formatResult: productForm ...

What are the effects of calling callback(false) and callback(true)?

I'm currently diving into a nodejs chat project, and Iā€™m a bit confused about the outcome when callback(false) and callback(true) are triggered in this context... io.sockets.on('connection', function(socket){ socket.on('new user& ...

I require displaying the initial three letters of the term "basketball" and then adding dots

Just starting out with CSS and struggling with the flex property. Seems to work fine at larger sizes, but when I reduce the screen size to 320px, I run into issues... Can anyone help me display only the first three letters of "basketball ...

Adding an additional stroke to a Material-UI Circular Progress component involves customizing the styling properties

I am attempting to create a circular progress bar with a determinate value using Material-UI, similar to the example shown in this circular progress image. However, the following code does not display the additional circle as the background: <CircularP ...

Retrieve HTML classes within JavaScript textual templates

<!-- TEMPLATE UPLOAD --> <script id="template-upload" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-upload fade"> <td class="name"><span>{%=file.name%}</span></td> <td ...

Retrieve data from two databases and display the information from two separate arrays on a single ejs page after making two separate database calls

Currently, I am faced with a challenge where I need to render a page by passing two arrays that are populated by two separate database calls. It seems that when I only pass one array to the ejs page, everything works as expected. For a single array, my a ...