¿Cómo usar map() en una array en orden inverso con JavaScript?

Dada una array de JavaScript, la tarea es aplicar el método map() pero en el reverso de la array de manera eficiente. Aquí hay algunos enfoques discutidos. Si no desea cambiar la array original, puede crear una copia superficial de la array y luego puede realizar la tarea.

Enfoque 1: la idea es usar el método .reverse() justo después de aplicar el método .slice() . Luego use el método .map() en la array invertida para realizar la tarea.

  • Ejemplo: Este ejemplo implementa el enfoque anterior.

    <!DOCTYPE HTML>
    <html>
      
    <head>
        <title>
            How to use map() on an array in
            reverse order with JavaScript ?
        </title>
      
        <style>
            body {
                text-align: center;
            }
            h1 {
                color: green;
            }
            #geeks {
                font-weight: bold;
            }
        </style>
    </head>
      
    <body>
        <h1>GeeksforGeeks</h1>
          
        <p>
            Click on the button to use
            <b>map()</b> on array in 
            <b>reverse</b> order<br>
            Array = [1, 3, 5, 7, 9, 10];
        </p>
          
        <button onclick="gfg_Run()">
            Click Here
        </button>
          
        <p id="geeks"></p>
          
        <script>
            var el_down = document.getElementById("geeks");
            var arr = [1, 3, 5, 7, 9, 10];
      
            /* Main function */
            function gfg_Run() {
                newArr = arr.slice(0).reverse().map(
                    function(val, index) {
                        return val * 2;
                    }
                );
                  
                el_down.innerHTML = "New Array = ["
                                    + newArr + "]";
            }
        </script>
    </body>
      
    </html>
  • Producción:

Enfoque 2: En este enfoque, usaremos el método .map() y llamaremos a una función dentro de este método con 2 argumentos (valor, índice) . Ahora necesitamos acceder al valor, accederemos desde el reverso (p. ej., arr[arr.length – 1 – index]), esta es una operación inmutable (no cambia la array original).

  • Ejemplo: Este ejemplo implementa el enfoque anterior.

    <!DOCTYPE HTML>
    <html>
      
    <head>
        <title>
            How to use map() on an array in
            reverse order with JavaScript ?
        </title>
          
        <style>
            body {
                text-align: center;
            }
            h1 {
                color: green;
            }
            #geeks {
                font-weight: bold;
            }
        </style>
    </head>
      
    <body>
        <h1>GeeksforGeeks</h1>
          
        <p>
            Click on the button to use 
            <b>map()</b> on array in 
            <b>reverse</b> order<br>
            Array = [8, 5, 15, 70, 9, 10];
        </p>
          
        <button onclick="gfg_Run()">
            Click Here
        </button>
          
        <p id="geeks"></p>
          
        <script>
            var el_down = document.getElementById("geeks");
            var arr = [8, 5, 15, 70, 9, 10];
              
            /* Main function */
            function gfg_Run() {
                newArr = arr.map((val, index, array) => 
                        1/2*arr[arr.length - 1 - index]);
                  
                el_down.innerHTML = "New Array = ["
                                    + newArr + "]";
            }
        </script>
    </body>
      
    </html>
  • Producción:
  • Publicación traducida automáticamente

    Artículo escrito por PranchalKatiyar 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 *