12


I am attempting to remove a value from an array using splice. starting at 0 and ending at 0 splice, but it is not removing the value at index 0. I added a function getItemRow to check the species index which returns 0. I dumped the values of the array into an alert and it still outputs species which should of been deleted. invalidElement.splice(indexValue, indexValue); works as expected for indexes that are NOT 0. Why is this happening and how do I delete the value that has 0 index?

javascript code:

var invalidElement = new Array("species", "alias", "gender", "breeding", "birth_date");

//This function will be removed once fixed!!
function getItemRow()
{
    var myPosition=-1
    for (i=0;i<invalidElement.length;i++)
    {
        if(invalidElement[i]=="species") {
            myPosition = i;
            break;
        }
    }
    alert(myPosition)
}

function validateElement(formId, element, selector, errorContainer)
{
    getItemRow()//for testing purposes
    //var indexValue = $.inArray(element, invalidElement);
    var indexValue = invalidElement.indexOf(element);

    alert(element);
    $.ajax({
        type: 'POST',
        cache: false,
        url: "validate_livestock/validate_form/field/" + element,
        data: element+"="+$(selector).val(),
        context: document.body,
        dataType: 'html',
        success: function(data){
            if (data == "false")
            {
                $(errorContainer).removeClass('element_valid').addClass('element_error');
                invalidElement = element;
                alert(invalidElement.join('\n'))//for testing purposes
                //alert(indexValue);
            }
            else
            {
                $(errorContainer).removeClass('element_error').addClass('element_valid');
                invalidElement.splice(indexValue, indexValue);
                alert(invalidElement.length);//for testing purposes
                alert(invalidElement.join('\n'))//for testing purposes
            }
        }
    });
}

$("#species").change(function(){
    validateElement('#add_livestock', 'species', '#species', '.species_error_1')
});
scottt
  • 7,008
  • 27
  • 37
dottedquad
  • 1,371
  • 6
  • 24
  • 55

4 Answers4

16

I think you want splice(0, 1).

The second argument is how many you want removed...

An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.

Source.

alex
  • 479,566
  • 201
  • 878
  • 984
13

Splice can work in two modes; to remove or insert items.

When removing items you'll specify two parameters: splice(index, length) where index is the starting index, and length is a positive number of elements to remove (fyi: passing a "0", as in your example, does nothing--it's saying "remove zero items starting at index"). In your case you'll want:

invalidElement.splice(indexValue, 1); // Remove 1 element starting at indexValue

When inserting items you'll specify (at least) three parameters: splice(index, length, newElement, *additionalNewElements*). In this overload you normally pass 0 as a 2nd parameter, meaning to insert the new elements between existing elements.

 var invalidElements = ["Invalid2", "Invalid3"];
 invalidElements = invalidElements.splice(0, 0, "Invalid1");
STW
  • 44,917
  • 17
  • 105
  • 161
  • If you want to insert an array of elements check out this answer: http://stackoverflow.com/a/12189963/984780 – Luis Perez Aug 31 '12 at 14:51
11

There's also a convenience function for removing the first element in an array:

array.shift();

See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift.

David Tang
  • 92,262
  • 30
  • 167
  • 149
0

Mozilla Dev Center - Array.splice states that the second parameter is 'howMany' elements to remove.

I'm not sure how your code worked when it passed in the indexValue as the number of elements to remove, unless you were removing from the end of the array.

typo.pl
  • 8,812
  • 2
  • 28
  • 29
  • ...it would be an interesting bug. If `indexValue === 1` then it would remove 1x item starting at index 1. If `indexValue === 2` then it would remove 2x items starting at index 2, and so on. – STW Mar 03 '11 at 22:49
  • haaa, I think you meant exactly – Brian Jun 07 '13 at 06:56