eliminar un elemento de un array in javascript

To remove an element from an array in JavaScript, you can use the splice() method. The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements. The syntax for splice() is as follows:

index.tsx
array.splice(start, deleteCount, item1, item2, ...)
52 chars
2 lines

Where:

  • start is the index at which to start changing the array (with origin 0).
  • deleteCount is the number of elements to remove from the array.
  • item1, item2, ... are the elements to insert into the array, beginning at the start index.

To remove a single element at a specific index, you can set deleteCount to 1 and omit any items to insert:

index.tsx
const array = ['a', 'b', 'c', 'd'];
const indexToRemove = 2;    // remove 'c'

array.splice(indexToRemove, 1);

console.log(array);    // Output: ['a', 'b', 'd']
162 chars
7 lines

In the example above, we first define an array array with four elements. We then define the index at which we want to remove an element (indexToRemove), which in this case is 2 (since arrays are 0-indexed, this refers to the third element of the array). Finally, we call splice() on the array, passing in indexToRemove as the start index and 1 as the deleteCount, which removes the element at that index. The resulting array contains the remaining elements (in this case, 'a', 'b', and 'd').

gistlibby LogSnag