How can I cut an array by value in Vue?

I am working on a component that has a list of objects and I need to implement functionality where, when toggled, the objects' title prop is either added to or removed from an array. Adding the value was easy to do, but removing it has proven challenging because the items can be selected and pushed onto the array in any order:

data

data () {
    return {
        options = [
            {
                title: "cookies",
                isSelected: false
            },
            {
                title: "cakes",
                isSelected: false
            },
            {
                title: "brownies",
                isSelected: false
            }
        ],
        selected : []
    }
},

template

<template>
    <div>
        <div
            v-for="(item, index) in options"
            :key="index"
            v-on:click="toggleSelected(index, item)">
            {{ item.title }}
        </div>
    </div>
</template>

script

toggleSelected: function (index, item) {
    item.isSelected = !item.isSelected

    if (this.selected.includes(item.title)) {
        return this.selected.splice(item.title) // trying to remove item.title, but not working as expected
    }
    return this.selected.push(item.title)
}

I realize my use of splice might be incorrect, so I'm seeking advice on how to achieve the desired outcome, with or without using splice.

Answer №1

Is it not a viable option to just remove it from the selection?

this.selectedItems = this.selectedItems.filter(item => item.id !== selectedItem.id);

Answer №2

The necessary arguments for the splice function include the starting index and the number of elements to remove

This implies that you need to execute a code similar to this:

this.selected.splice(this.selected.indexOf(item.title), 1);

Answer №3

When using the splice method, remember that the correct form is (index, count, insert). The parameter insert changes the function's behavior to add to the array instead of removing from it. To apply the splice method in this scenario, you'll need to first find the index of the item and then specify that you want to remove one item by omitting the last parameter.

const index = this.selected.indexOf(item.title)
if (index > -1) {
  this.selected.splice(index, 1);
}

Alternatively, filter can be used as a simpler alternative solution that I recommend opting for in this case.

this.selected = this.selected.filter(title => title !== item.title)

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

Using AJAX to retrieve data from PHP consisting of two arrays and a string

When using AJAX to pass 2 arrays (each containing values from checkboxes) and a string (from a search textbox) to PHP, it's important to ensure the data is correctly formatted. The arrays selectedCategories and selectedCompanies are both arrays, whil ...

Adding a C# variable to a URL in a Razor view using jQuery

My Razor page looks like this: @{ ViewData["Title"] = "mypage"; string ApiAddress = "https://localhost:8114/api/"; } <div> ... </div> @section Scripts{ <script> functio ...

Attempting to display a grid of product listings using a Websocket connection and an Express server

Recently, I attempted to create a live table of products using websockets for real-time updates. While I am new to this concept, I decided to upgrade an old project with websockets. Unfortunately, my attempts were unsuccessful, which is why I am seeking he ...

Ways to combine extensive value within an array containing various objects

I am working with an array of objects and I need to merge all the values of params within each object into a single object. Array [ Object { "key": "This week", "params": Object { "thisWeekfilterDistance": [Function anonymous], "this ...

Leveraging AngularJS directives and $scope autonomously

Let me provide some context first: Previously, my focus was on developing lightweight, single-page Angular applications. However, in the past few days, I began working on a new project that combines Tapestry and Backbone. It has proven to be quite overwhe ...

What is the best way to implement setState in this scenario?

Receiving warnings in the console that say: Avoid changing state directly. Instead, use setState() method: react/no-direct-mutation-state When I tried changing this.state.turn = this.state.turn === 'X' ? 'O' : 'X'; to this.s ...

The authentication method "discord" is not recognized

Currently, I am working on implementing discord authentication using passport. Originally, everything was functioning correctly, but now it seems to have encountered an issue which I cannot identify. auth.js const express = require('express') co ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

What is the best way to maintain the selected radio button on the following page using PHP?

Image of My Project I am working with a file and need some assistance. I want to ensure that when a user selects an answer, the radio button value remains unchanged if they click back. Can someone please help me with this? while( $row = mysqli_fetch_arra ...

The function call to 'import firebase.firestore()' results in a value

I recently set up a Vue App with the Vuefire plugin. Here is an example of my main.js file, following the documentation provided at: : import Vue from 'vue' import App from './App.vue' import router from './router' import sto ...

What is the best way to generate unique mousedown callbacks on the fly?

My goal is to create multiple divs, each with a unique mousedown callback function. However, I want each callback function to behave differently based on the specific div that is clicked. Below is the code I have been using to create the divs and set the ...

Exporting NativeModules for npm package in React Native

I'm attempting to convert my React Native App into a node module. The issue I'm facing is that the module consists mainly of a NativeModule. Thus, my index.js file appears like this: import { NativeModules } from 'react-native'; expo ...

What is the best way to adjust the size of an image within a block layout using either JavaScript or React?

I have a game to create, and I need a block of elements to be aligned like the image below. However, the kangaroo image is not displaying correctly. The actual size of the image is width:70px and height:100px. But I want to resize it to width: 49px and h ...

Make sure that the iframe loads the next page with enough force to break out

My dilemma involves an iframe that loads the new tab page. When a user clicks on the thumbnail, it opens within the iframe. My goal is to have any subsequent load in the iframe redirected to window.top. Is there a way to achieve this without manually setti ...

Steps for inserting API data into a MySQL database

I am currently working on a project and need help figuring out how to integrate my API results into MySQL. You can find the results on this page. Below is the code snippet from the page: <?php ///PLOT PROJECT USER REQUEST //FUNCTION TO DEBUG IN ...

Finding the correlation between SVG element IDs and JSON keysUnderstanding how to pair up

Currently, I have an SVG file that can be viewed here. My goal is to present specific data when elements within the SVG are clicked. The data is in JSON format and I am looking to match each ID of an SVG element with a key in the JSON data. If both the key ...

real-time update of gauge value from soap

I am trying to update the value shown in my justgage widget with the value returned from $("#spanrWS_Measured").text(data[0]);. The current value is 123. Any assistance would be greatly appreciated. See the complete code below. <script src="scripts/r ...

The Art of Validating Forms in Vue.js

Currently I am in the process of developing a form with validation using Vue, however, I've run into some errors that are showing up as not defined even though they are currently defined. HTML <form class="add-comment custom-form" @submit="checkF ...

Combine two sets of 2D arrays by merging the rows that have matching values in a specific column

I am looking for a way to merge two arrays without removing any elements from either array. Array1 will always include date and price1 elements, while array2 will always have date and price2 elements. If both arrays contain the same date (e.g., 1-Sep-2016) ...

Encoding identification data from JSON using ColdFusion

Hello everyone, I've been puzzling over how to intercept and encrypt database record ID from a JSON request in ColdFusion. Below is the code I have so far, along with my unsuccessful attempt. Any assistance would be greatly appreciated. <cfquery ...