Unable to remove an element from my Array during verification

http://plnkr.co/edit/b1v87pUEykOJN4mKLFHa?p=preview

My goal is to manage two arrays: one coming from an API called apiArray, and the other, toggleArray, will hold selected items from apiArray.

The function selectBtn is meant to toggle items in and out of the array. Currently, I am able to add items to toggleArray, but not remove them when clicking on the same button.

I'm looking for a more efficient way to check if an item is not in the array, then add it, and if it is in the array, then remove it.

var vs = $scope;
    vs.message = "Add and remove objects from array:";
    vs.toggleArray = [];
    var btnInArray = false;

    vs.apiArray = [
        { name: 'AAA' },
        { name: 'BBB' },
        { name: 'CCC' }
      ];

    vs.selectBtn = function(btnObj) {
      console.log(btnObj.name);

    function checkUpdateToggleTags(obj, list) {
            var i;
            for (i = 0; i < list.length; i++) {
                if (list[i] === obj) {
                    return true;
                }
            }
            return false;
        }

        btnInArray = checkUpdateToggleTags(btnObj, vs.toggleArray);

        if (btnInArray) {

            // check the toggleArray and if obj from listToDelete is there
            // remove that obj from toggleArray
            for(var i = 0; i < vs.toggleArray.length; i++) {
                var obj = vs.toggleArray[i];

                if (vs.toggleArray.indexOf(obj.term) !== -1) {
                    vs.toggleArray.splice(i, 1);
                    i--;
                }
            }

        } else {
          vs.toggleArray.push(btnObj);
        }

        console.log(btnInArray);
        console.log(vs.toggleArray);
    };

Answer №1

You've overcomplicated things unnecessarily. Instead of reinventing the wheel, you can simply utilize Array.prototype.indexOf to search for objects in an array. With this approach, your selectBtn method can be simplified as follows:

vs.selectBtn = function(btnObject) {
    var index = vs.toggleArray.indexOf(btnObject);
    if (index !== -1) {
        vs.toggleArray.splice(index, 1);
    } 
    else {
        vs.toggleArray.push(btnObject);
    }
};

Check out the demo here: http://plnkr.co/edit/34KVRAAhuMdVteO9S1Qn?p=preview

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

Can Firestore data be filtered based on multiple user-selected values within an Angular application?

I'm in the process of creating a product filter that allows users to choose from various options without being required to select any. In my Firestore database, the structure is as follows: product { colour: "white" brand: "a brand" } Currently, I ...

Is it necessary for services in Domain Driven Design to have knowledge of other services, or should they be aware of multiple repositories

As I work on developing a backend application, my focus is on implementing the Domain Driven Design. However, there's a particular question I have regarding the data structure that requires some clarification. Database Configuration Users Id ( ...

Each time Firebase retrieves an object, it comes back with a unique name

One query has been bothering me: const questionsRef = firebase .database() .ref('Works') .orderByChild('firebaseKey') .equalTo(this.props.match.params.id); It's functional, but the issue lies in the output: "-LDvDwsIrf_SCwSinpMa ...

Tips on updating pinned row information in AG Grid Vue

I have a specific row pinned to the bottom in the grid. Whenever I add or remove some rowData in the grid, I need to update that pinned row. Take a look at the code snippet below: this.gridApi.pinnedBottomRowData = rowNode.setDataValue(date, dataToPush); t ...

Invoking a Vuex action inside another Vuex action

After transitioning to the Vuex store, I've been steadily moving forward. However, my current hurdle involves invoking an action from within another action in Vuex. My grasp on Vue.js is still a work in progress. Current versions Vue 3 Vuex 4 If nec ...

How can I accurately determine the Content-length header when using node.js?

How accurate is my current approach to determining the content-length? What potential impacts are there when relying on string.length() for this calculation? And does specifying the charset as utf-8 have any significance in a node.js environment? payloa ...

Is there a way to bind data exclusively upon form submission in Angular2?

I am currently working on an Angular2 form that presents a challenge. <form (ngSubmit)="onSubmit()"> <input type="text" [(ngModel)]="userName"/> <button type="submit">Submit</button> <button>Cancel</button> < ...

What are the potential risks associated with including your backend server port number in your code?

Working on a project using React and Node.js here. My server is set up with Express and the dotenv package to keep my server configurations secure, like the PORT number where my backend server operates. For instance, my server's environment variable i ...

No Backend Detected for Tensorflow.js in Node

I've been attempting to develop a Discord bot that utilizes the @tensorflow-models/qna library, but I've hit a roadblock for the past 4 hours. Every time I run the script below: const qna = require('@tensorflow-models/qna'); (async () ...

I need help figuring out how to successfully play a large PCM file using AudioTrack as I am encountering errors

Recently, I've been diligently working on some code for an app that I'm developing, and I've encountered an issue when trying to play large PCM files (exceeding 600mb). The current implementation of my play() method looks like this: public ...

Find the variance between two arrays containing distinct elements

I have 2 arrays with a similar structure as shown below. My objective is to compare each field and store the items from the arrays that differ in a third array. Arr1= [{ state:CA, id:1, name:aaa, product:car, color: white}, {...}] and so forth Arr2= [{ id ...

Instructions for showcasing a specific entry from the json server db.json based on user input

Currently, I am capturing user input from an input component and I would like to display the corresponding information on a display component in my Angular application. The user records are stored in a JSON server named db.json. Does anyone know how I can ...

Is There a Sparse Array Element in JavaScript?

Is there a more efficient method to check for the presence of an array element within multiple layers of a structure? For example: if (typeof arr[a][b][c] === 'undefined') { ...do something... } If [a] or [b] are missing, we cannot accurately t ...

HTML display with two columns for books viewing

My Plan: I am working on incorporating HTML content from an external source into my app, displayed in a 2-column horizontal scrolling book format using a WebView element. I want it to resemble how the Edge browser presents an EPUB book, with seamless horiz ...

Safari is not properly handling element IDs when used in conjunction with React

I am currently in the process of building a straightforward single-page website utilizing React. At the top of the page, there is a navigation bar that contains links to various sections of the site: <li><a href="/#about">About u ...

Make a CSS div that expands based on the size of its absolutely positioned content

I'm currently experiencing some challenges trying to make a parent div expand to fit its contents which are positioned absolutely. The footer is reaching the bottom of the screen, but not the bottom of the document. This issue is clearly caused by th ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...

The debate between storing multiple references in a React component and querying the DOM by ID

While creating a form in React, I want to automatically focus on the first invalid field after submission. In order to achieve this, I need to have access to a reference of the invalid field and then call .focus() on it. My question is whether it would be ...

Multi-line D3 chart that dynamically updates and intersects with the axis

I am attempting to create a multiline d3 chart that can be updated with new datasets. I have developed a method to plot the new data on the existing d3 frame, but I am encountering issues when trying to update the chart with mocked data. The new data is no ...

What is the rationale behind storing animation settings in two distinct object literals within TweenMax?

While going through this Codepen, I came across the following code: var tmax_options = { repeat: -1, yoyo: true }; var tmax_tl = new TimelineMax(tmax_options), tween_options_to = { css: { transform: 'scale(0)', ...