Javascript: How do I splice a value from an array with an index of 0?

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.


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");

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.