Iterate through and remove elements within an array containing objects

Within my Vue.js application, I am working with an array of objects that I need to iterate through and display in the web browser. The array consists of four objects, but I only wish to show three based on a user's preference setting stored in a variable (referred to as userPreference). I'm currently facing the challenge of efficiently removing one object from the array depending on the value of userPreference.

This is how I have implemented the v-for in my template:

<ul v-for="item in getOutroItems"><li>item<li></ul>

Here is my object structure:

data() {
return {
  outroItems: [{ title: "outro1", text: "XYZ" }, { title: "outro2", text: "ABC" }, { title: "outro3", 
               text`: "QRS" }, { title: "outro4", text: "TUV" }],
  userPreference: ""
};

}

This is my current computed property setup:

getOutroItems() { 
   this.outroItems.filter((value) => {
     if(this.userPreference === "newsletter") {
        /// Remove outro2 from the array here and return the remaining three values
     } else if(this.userPreference === "noNewsletter") {
        /// Eliminate outro3 from the array and return the rest of the values
     }
   })
}

I am seeking guidance on the most effective method for eliminating a specific element from an array. Any insights or clarifications would be greatly appreciated!

Answer №1

To satisfy your requirement, you can use the following code with array.filter. This method only requires true or false in its return to determine whether to keep or remove an element from the array.

getOutroItems() { 
   this.outroItems.filter((value) => {
     if(this.userPreference === "newsletter") {
        // Remove outro2 and return an array with the other 3 values
      return value.title != 'outro2';
     } else if (this.userPreference === "noNewsletter") {
        // Remove outro3 and return an array with the other 3 values
    return value.title != 'outro3';
     }
   })
}

If you want to avoid creating another large array, you can swap the elements to be removed with the last indexed element in the array and then pop those elements from the array.

Answer №2

There are various ways to extract the correct elements from an array.

The method I prefer and in this example: Utilizing array.filter

const outroItems = [
  { title: "outro1", text: "XYZ" },
  { title: "outro2", text: "ABC" },
  { title: "outro3", text: "QRS" },
  { title: "outro4", text: "TUV" }
];

const leftOverItems = outroItems.filter((item) => item.title !== "outro2");

console.log(leftOverItems);

Another approach is to identify the index of the item to be removed and then delete it using splice

const outroItems = [
  { title: "outro1", text: "XYZ" },
  { title: "outro2", text: "ABC" },
  { title: "outro3", text: "QRS" },
  { title: "outro4", text: "TUV" }
];

const itemToDelete = outroItems.find((item) => item.title === "outro2");
const indexToDelete = outroItems.indexOf(itemToDelete);

outroItems.splice(indexToDelete, 1);

console.log(outroItems);

By combining any of the aforementioned functions with a function, you can avoid duplicating code.

const itemToRemove = (arr, attr, name) => {
  return arr.filter((item) => item[attr] !== name);
}

const outroItems = [
  { title: "outro1", text: "XYZ" },
  { title: "outro2", text: "ABC" },
  { title: "outro3", text: "QRS" },
  { title: "outro4", text: "TUV" }
];

// Remove items from "outroItems" where "title" is "outro2"
const removed2 = itemToRemove(outroItems, "title", "outro2");
// Remove items from "outroItems" where "title" is "outro3"
const removed3 = itemToRemove(outroItems, "title", "outro3");
// Remove items from "outroItems" where "text" is "TUV"
const removedTUV = itemToRemove(outroItems, "text", "TUV");

console.log(removed2);
console.log(removed3);
console.log(removedTUV);

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

Search field in DataTables appears to be misaligned

I'm in the process of developing a small website using JSP and DataTables (currently only for the first table). Here's what I have so far: As you can observe, there seems to be an alignment issue with the search field position. I'm n ...

HTML generated in the header of a bootstrap-vue table

I'm currently developing a website using NuxtJS, Bootstrap Vue, and vue-i18n. Within the site, I have a table (<b-table>) that displays areas in square meters. The header of this table should show "sq m" in English and "m2" (m<sup>2</s ...

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

What exactly is HTML cloud storage all about?

As I work on developing an app through phonegap, one question that comes to mind is the possibility of storing information online. For instance, if there's a number variable that increases when a button is pressed, can this value be saved somewhere an ...

What is the process for sending a selected option using AJAX?

Using Ajax within Laravel to save data involves a form with input fields and a select option. Here is the form structure: <form class="forms" method="get" action=""> {{ csrf_field() }} <div class="form-group row ...

How can I use JavaScript to create a drop-down menu that only appears after selecting the previous one?

<div class="row"> <div class="col-md-4"> <label for="selectCustomers">Customer Select</label> <select class="form-control pointer" name="tableCustomers" id=" ...

Listening to React events on multiple elements in an array

When my React render function is running, it ends up rendering a group of elements: data.map((element) => { return <Object onChange={this.onObjectChange} />; }); I'm wondering, what is the best approach to determine which specific object ...

From converting Javascript code to PHP and using the innerHTML function for deletion

I'm currently working on implementing a script and could use some assistance with two specific issues that I'm struggling to resolve. The main goal is to enable users to create a running route and then store the route in a database using coordina ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...

What is the best way to iterate through a JSON object and display its values?

When I receive JSON data from an API, it looks like this: callback({"Message":"","Names”:[{“id”:”16359506819","Status":"0000000002","IsCurrent":true,"Name":"JAKE"," ...

Troubleshooting Pagination Challenges in Node.js Using Mongoose and Enhancing Query Performance

Having trouble with my database query using Mongoose. I am setting values but not getting the correct result, and I also want to optimize the query. Currently, I am using mongoose to count how many records match certain query parameters for pagination, whi ...

Receive regular position updates every second in React Native

Currently, my code is functional but lacks reliability. I often encounter delays and sometimes it doesn't update at all. My goal is to achieve real-time position updates. To accomplish this, I have utilized the setInterval() function within the compon ...

Using the ternary expression in v-model to access the value of an object

I am having trouble using a ternary expression with v-model. In this code example, I can access the data value (name:'data_value') inside data(), but I cannot access "detailCompanyDatas.smCompany.name". What should I do? Thanks <v-text-field ...

Node.js error message: Unable to load HTTP module

Recently starting with Node.js, I decided to install the latest version (4.2.1) on my Windows 7 PC. However, when trying to include the HTTP module by writing: var http = require("http"); I'm receiving an undefined error message. Can someone help me ...

Obtaining a specific item from a group using AngularJS. Utilizing a declarative method

Consider a scenario where you need to apply a CSS rule to a specific element within a collection that needs to be selected. <div ng-repeat="fragments" ng-click="makeSelected()"></div> $scope.fragments = [ {id: 6379, someProperty: "someValu ...

"Enhance the visualization of your data with Apexcharts by accurately coloring the columns

When attempting to color the graphic using an array, only one color is applied to all three columns, despite declaring a different color for each column. options: { chart: { type: 'bar', id: 'chart', }, colors: ['#3 ...

Is the Positioning of JS Scripts in Pug and Jade Documents Important?

Have you ever wondered why a page loads faster when certain lines are placed at the end of the tag instead of inside it? script(src="/Scripts/jquery.timeago.js") This phenomenon is often seen in code like this: //Jade file with JQuery !!! 5 html(lang=" ...

What steps can I take to help EventListener locate a specific class if it is experiencing difficulty?

In the process of creating a responsive navigation bar, everything seems to be functioning correctly except for a small javascript error that arises in my sub menu when clicking. Despite thoroughly checking through my index, script, and style files, I am ...

jQuery load() function triggers unexpected error in jQuery plugin

Here is the current structure of my page: <body> <div id="menuBar"> </div> <canvas id="myCanvas" width="700" height="700" style="border:1px solid #000000;"></canvas> </body> <script src="../Scripts/jQuery.mazeBo ...

When a text is wrapped by an HTML div using absolute positioning, is there a way to prevent it from wrapping without relying on white space

I have a group of div elements positioned absolutely on the screen. If any div contains content that is too big for the screen, the browser wraps it into multiple lines to fit. However, I do not want this behavior. Instead, I want the overflowing content ...