Removing an item from an array using AngularJS with Underscore or another method

Although my question may seem similar to others, it is unique!

Please review to understand my specific situation.

I am dealing with an array of objects that looks like this

$scope.events =[
    {
        $$hashKey: "009"
        _allDay:false
        _id:5
        allDay:false
        className:[]
        end:Date {Fri Aug 08 2015 12:30:00 GMT+0530 (IST)}
        start:Date {Fri Aug 08 2015 12:30:00 GMT+0530 (IST)}
        title:"Birthday Party"
    },
    {
        $$hashKey:"006"
        _id:2
        end:Date {Wed Aug 05 2015 00:00:00 GMT+0530 (IST)}
        start:Date {Sun Aug 02 2015 00:00:00 GMT+0530 (IST)}
        title:"Long Event"
    },
    {
        $$hashKey:"007"
        _id:3
        allDay:false
        id:999
        start:Date {Fri Aug 07 2015 13:00:00 GMT+0530 (IST)}
        title:"Angular Event"
    },
    {
        $$hashKey:"008"
        _id:4
        allDay:false
        id:999
        start:Date {Tue Aug 11 2015 16:00:00 GMT+0530 (IST)}
        title:"Repeating Event"
    },
    {
        $$hashKey:"00A"
        _id:6
        end:Date {Sat Aug 29 2015 00:00:00 GMT+0530 (IST)}
        start:Date {Fri Aug 28 2015 00:00:00 GMT+0530 (IST)}
        title:"Click for Google"
    }
]

Now my task is to remove an object from this array, which looks like this

var selectedObj = {
    $$hashKey:"009"
    _allDay:false
    _id:5
    allDay:false
    className:[]
    end:Date {Fri Aug 07 2015 12:30:00 GMT+0530 (IST)}
    start:Date {Fri Aug 07 2015 12:00:00 GMT+0530 (IST)}
    title:"Birthday Party"
}

My approach to removing the object is as follows

removedArray = _.reject($scope.events, function(event) {
   return event.$$hashKey == selectedObj.$$hashKey
});

$scope.events = removedArray;

$scope.events does not update even after trying $apply.

Could someone assist me in identifying any mistakes I may have made?

What would be the best practice for handling such issues?

Answer №1

If you're looking to achieve this task using basic JavaScript (compatible with IE9 and above), you can use the following code snippet:

var index = myArray.map(function(element) { return element.$$hashKey; }).indexOf(selectedObject.$$hashKey);

if(index != -1) {
    myArray.splice(index, 1);

On the other hand, if you prefer to utilize underscore.js, you could opt for a solution similar to this:

myArray = _(myArray).filter(function(object) {
     return object.$$hashKey !== selectedObject.$$hashKey;
});

Answer №2

If you're looking for a cleaner solution, you can consider using lodash's remove function. It works similarly to the code provided by dustmouse, but in my view, it offers better readability.

var selectedObj = {...}
$scope.events = [0,1,...,n];

$scope.events = _.remove($scope.events, function(element) {
  return element == selectedObj;
});

Answer №3

If you want to remove the chosen event, simply use the deleteEvent function.

$scope.deleteEvent = function() {
    var position = $scope.events.indexOf(selectedObj);
    $scope.events.splice(position, 1);
};

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

Utilize Quasar CSS breakpoints within Vue expressions for responsive design

I am currently using the QDialog component from Quasar Framework and I want to set the value of the maximized property based on the current screen size, specifically being maximized for small screens only. Is there a way for me to reference a variable in ...

Tips for making an image fill the entire screen with a header using React Navigation

My screen includes an image and I would like to capture the full-size screen with the header displayed. However, using position: "absolute" does not properly wrap the header, and setting header: null is not an option since I still want the back button to b ...

failure of svg spinning

I'm currently working with an SVG file and attempting to incorporate a spinning animation similar to loaders and spinners. However, I am facing an issue where the rotating radius is too large and I am struggling to control it effectively. CSS: .image ...

Issues with Collision Detection between Canvas Rectangles and Balls

I am developing an HTML5 canvas game and encountering an issue with collision detection. The problem occurs when the ball collides with any platform - the ball's gravity should change to -1 and move upwards at the same velocity as the platforms. Howev ...

Are queued events in React discarded upon a state change?

As I develop a React form component with simple validation, I encounter an issue where the onBlur event of a field and the onSubmit function of the form are triggered simultaneously. If there is a change in the state during onBlur, the onSubmit function do ...

HTML form with a dropdown menu

Imagine you have a HTML form containing two dropdown lists. The first dropdown is labeled "country" and contains a list of countries. The second dropdown, labeled "cities," should be dynamically populated based on the country selected. What is the best ...

What are the different ways to retrieve elements within a numpy ndarray?

When loading a matlab data file into python using the loadmat function from scipy, the resulting fields variable is of type numpy.ndarray: from scipy.io import loadmat data = loadmat('data.mat') fields = data['field'] fields ty ...

Struggling to get a shader up and running on three.js using shaderfrom

Trying to add this shader to my project: This is the fragment shader code: <script id="fragmentShader" type="x-shader/x-fragment"> #ifdef GL_ES precision highp float; precision highp int; #endif uniform vec2 u_resolutio ...

Choosing different elements using identical classes in JQuery

Struggling with a coding problem that seems like it should be an easy fix, but can't quite figure it out. The HTML code I have is as follows: <section class="actualite"> <div class="actualite-text"> <h3 class="title"&g ...

Converting a child.jsp file into a modal or overlay using JavaScript: A step-by-step guide

Is it possible to call a child.jsp as a model using JavaScript? I previously accessed the child jsp using showmodaldialog and window.open() with JavaScript, but it opens in another window. I want the child jsp to appear in a modal or overlay view. Can some ...

Troubleshooting Subtle Validation (on the front end)

After implementing unobtrusive validation, I noticed that my form appears error-free upon initial inspection. However, when I execute the following code: $(valForm).valid(); The result returned is false. To troubleshoot this issue, I want to determine ...

Guide to setting up a backend system using AJAX, PHP, and MySQL to handle dynamic video sources in conjunction with Google TV Templates

If you're looking to develop web apps for Google TV, particularly those involving video content, the simplest method is to utilize Google TV Templates: https://developers.google.com/tv/web/docs/gtv-templates. The original Google TV Templates included ...

Determine the total value of various dynamic elements by utilizing jQuery/Javascript for calculation

I am currently working on a project that involves a dynamic list of products in a cart. I need to calculate the total price of all the products in the cart, but I am having trouble figuring out how to access and calculate the values from these dynamic elem ...

Unlock Buffer - JavaScript

I'm working with a simple JavaScript code snippet. let str = "Hello World"; console.log(Buffer.from(str,"utf-8")); The output is: <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64> Is there a way to extract the bytes from the Buffe ...

Leverage PHP to integrate JSON data for consumption by JavaScript

I've been exploring the integration of React (JavaScript) within a WordPress plugin, but I need to fetch some data from the database for my plugin. While I could retrieve this data in JavaScript using jQuery or an API call, because the data will remai ...

Sequelize.js keeps the previous value for linked tables

My objective is to update the product status within the Product table. Each product has a statusId, which is either "1" or "2". The default value for statusId is always set to "1" for all products and should switch to "2" when the route is accessed once (a ...

Troubleshooting a dysfunctional collapsed navbar in React with Bootstrap 5

I am experiencing an issue where the collapsed navbar icon does not expand when clicked on smaller screens. I followed the example provided by bootstrap 5 and made sure to include bootstrap css/js and jquery. class CustomNavBar extends Component { re ...

When an onClick event is triggered in jQuery, generate a certain number of div blocks based on the available list items, such as image source and heading text

Is it possible to generate input fields dynamically based on a dynamic list with checkboxes, labels, text, images, etc.? I currently have a working solution for checkboxes and labels using the code snippet below: let $checkboxContent = $('.checkboxes ...

Displaying different elements using an anchor <a> tag

Within this example, I've created two functional components that mimic separate pages with differently colored <div> boxes. const Home = () => <div style={{background:'red', height: 100, width: 100}}></div>; const ...

Ways to recycle a section of Javascript for multiple uses on a single page

As a newcomer to website building, I have a query regarding the usage of a JavaScript function designed for a slideshow. My one-page website comprises multiple slideshow units with their own divs, holders, and counters (e.g., 1/4). A JavaScript code contro ...