¿Cómo insertar un elemento en una array en un índice específico en JavaScript?

No existe un método incorporado en JavaScript que permita directamente la inserción de un elemento en cualquier índice arbitrario de una array. Esto se puede resolver usando 2 enfoques:

Uso de array.splice():
el método array.splice() generalmente se usa para agregar o eliminar elementos de una array. Este método toma en 3 parámetros, el índice donde se insertará o eliminará la identificación del elemento, la cantidad de elementos que se eliminarán y los nuevos elementos que se insertarán.

La única inserción se puede realizar especificando el número de elementos que se eliminarán en 0. Esto permite insertar solo el elemento especificado en un índice particular sin eliminación.

Sintaxis:

array.splice(index, no_of_items_to_remove, item1 ... itemX)

Ejemplo:

<!DOCTYPE html>
<html>
  
<head>
    <title>
      How to insert an item into
      array at specific index in JavaScript?
  </title>
</head>
  
<body>
    <h1 style="color: green">
      GeeksforGeeks
  </h1>
    <b>How to insert an item into array 
      at specific index in JavaScript?</b>
    <p>The original array is: 1, 2, 3, 4, 5</p>
    <p>Click on the button to insert -99 at index 2</p>
    <p>The new array is: <span class="outputArray"></span>
  </p>
  
    <button onclick="insertElement()">Insert element</button>
    <script type="text/javascript">
        function insertElement() {
            let arr = [1, 2, 3, 4, 5];
            let index = 2;
            let element = -99;
  
            arr.splice(index, 0, element);
            document.querySelector('.outputArray').textContent =
              arr;
        }
    </script>
</body>
  
</html>

Producción:

  • Antes de hacer clic en el botón:
    before-insert
  • Después de hacer clic en el botón:

Uso del bucle for tradicional:
el bucle for se puede usar para mover todos los elementos desde el índice (donde se insertará el nuevo elemento) hasta el final de la array, un lugar después de su lugar actual. El elemento requerido se puede colocar en el índice.

Código:

// shift all elements one place to the back until index
for (i = arr.length; i > index; i--) {
    arr[i] = arr[i - 1];
}
 
// insert the element at the index
arr[index] = element;

Ejemplo:

<!DOCTYPE html>
<html>
  
<head>
    <title>How to insert an item 
      into array at specific index
      in JavaScript?</title>
</head>
  
<body>
    <h1 style="color: green">
      GeeksforGeeks
  </h1>
    <b>How to insert an item into
      array at specific index in JavaScript?
  </b>
    <p>The original array is: 1, 2, 3, 4, 5
  </p>
    <p>Click on the button to insert -99 at index 2
  </p>
    <p>The new array is: <span class="outputArray"></span>
  </p>
  
    <button onclick="insertElement()">
      Insert element
  </button>
    <script type="text/javascript">
        function insertElement() {
            let arr = [1, 2, 3, 4, 5];
            let index = 2;
            let element = -99;
  
            // shift all elements one
            // place to the back until index
            for (i = arr.length; i > index; i--) {
                arr[i] = arr[i - 1];
            }
  
            // insert the element at the index
            arr[index] = element;
  
            document.querySelector(
              '.outputArray').textContent = arr;
        }
    </script>
</body>
  
</html>

Producción:

  • Antes de hacer clic en el botón:
    before-insert2
  • Después de hacer clic en el botón:
    after-insert2

Publicación traducida automáticamente

Artículo escrito por sayantanm19 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *