Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splice can't remove the first element in javascript

In angular2, my HTML is calling removeThisForm in javascript. The event is an object of File Array. For each object in File Array, I generate a form in angular2.

(click)=removeThisForm(event)

In javascript, I am trying to remove the file that is passing in.

removeThisForm(file) {
    var removableIndex = arr.indexOf(file);
    if (removeIndex >= 0) {
        arr = arr.splice(removableIndex);
    } 

I am able to remove any form passing in, except the first one. I tried shift(), slice() and splice(0,1). When I did splice(0,1), I am getting an error of "Form submission canceled because the form is not connected".

like image 716
Matt-pow Avatar asked Mar 21 '17 15:03

Matt-pow


People also ask

How do you remove the first element from an array using splice?

To remove the first n elements from an array:Call the splice method on the array, passing it the start index and the number of elements to remove as arguments. For example, arr. splice(0,2) removes the first two elements from the array and returns a new array containing the removed elements.

How do you remove an element using splice?

The splice() function changes the contents of an array by removing existing elements and/or adding new elements. In splice the second argument is the number of elements to remove. splice modifies the array in place and returns a new array containing the elements that have been removed.

How do I remove the first element?

The shift() method removes the first item of an array.

How do I remove the first element from an array?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.


1 Answers

You've omitted to pass second argument to the Array.prototype.splice method (an integer representing the number of elements to be deleted). Try this:

removeThisForm(file) {
    var removableIndex = arr.indexOf(file);
    if (removeIndex >= 0) {
        arr.splice(removableIndex, 1);
    } 
}

Also, the Array.prototype.splice method returns an array containing the deleted elements. Therefore, you can't say:

arr = arr.splice(removableIndex, 1);

as it will override your arr with the returned value of Array.prototype.splice method.

like image 92
seidme Avatar answered Oct 11 '22 02:10

seidme