Iteración de matriz de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


Los métodos de iteración de matrices operan en cada elemento de la matriz.


Matriz de JavaScript forEach()

El método forEach() llama a una función (una función de devolución de llamada) una vez para cada elemento de la matriz.

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);

function myFunction(value, index, array) {
   
txt += value + "<br>";
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>

<p>Call a function once for each array element:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];

let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;

function myFunction(value, index, array) {
  txt += value + "<br>"; 
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 3 argumentos:

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí

El ejemplo anterior utiliza sólo el parámetro de valor. El ejemplo se puede reescribir. a:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);

function myFunction(value) {
   
txt += value + "<br>"; 
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>

<p>Call a function once for each array element:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];

let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;

function myFunction(value) {
  txt += value + "<br>"; 
}
</script>

</body>
</html>

Matriz de JavaScript mapa()

El método map() crea una nueva matriz realizando una función en cada elemento de la matriz.

El método map() no ejecuta la función para la matriz Elementos sin valores.

El método map() no cambia la matriz original.

Este ejemplo multiplica cada valor de matriz por 2:

Ejemplo

const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
  
function myFunction(value, index, array) {
    return value * 2;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The map() Method</h2>

<p>Create a new array by performing a function on each array element:</p>

<p id="demo"></p>

<script>
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

document.getElementById("demo").innerHTML = numbers2;

function myFunction(value, index, array) {
  return value * 2;
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 3 argumentos:

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí

Cuando una función de devolución de llamada usa solo el parámetro de valor, el índice y la matriz Los parámetros se pueden omitir:

Ejemplo

const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
  
function myFunction(value) {
    return value * 2;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The map() Method</h2>

<p>Create a new array by performing a function on each array element:</p>

<p id="demo"></p>

<script>
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

document.getElementById("demo").innerHTML = numbers2;

function myFunction(value) {
  return value * 2;
}
</script>

</body>
</html>

Matriz de JavaScript mapa plano()

ES2019 agregó el método Array flatMap() a JavaScript.

El método flatMap() primero asigna todos los elementos de una matriz y luego crea una nueva matriz aplanando la matriz.

Ejemplo

const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap((x) => x * 2);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The flatMap() Method</h2>

<p id="demo"></p>

<script>
const myArr = [1, 2, 3, 4, 5,6];
const newArr = myArr.flatMap((x) => x * 2);
document.getElementById("demo").innerHTML = newArr;
</script>

</body>
</html>

Soporte del navegador

JavaScript Array flatMap() es compatible con todos los navegadores modernos desde enero de 2020:

Chrome 69 Edge 79 Firefox 62 Safari 12 Opera 56
Sep 2018 Jan 2020 Sep 2018 Sep 2018 Sep 2018


Matriz de JavaScript filtro()

El método filter() crea una nueva matriz con elementos de la matriz que pasan una prueba.

Este ejemplo crea una nueva matriz a partir de elementos con un valor mayor que 18:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {
  return value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The filter() Method</h2>

<p>Create a new array from all array elements that passes a test:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

document.getElementById("demo").innerHTML = over18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 3 argumentos:

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí

En el ejemplo anterior, la función de devolución de llamada no utiliza el índice ni la matriz. parámetros, por lo que se pueden omitir:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
const over18 = 
  numbers.filter(myFunction);
function myFunction(value) {
  return value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The filter() Method</h2>

<p>Create a new array with all array elements that passes a test.</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

document.getElementById("demo").innerHTML = over18;

function myFunction(value) {
  return value > 18;
}
</script>

</body>
</html>

Matriz de JavaScript reducir()

El método reduce() ejecuta una función en cada elemento de la matriz para producir (reducirlo a) un único valor.

El método reduce() funciona de izquierda a derecha en la matriz. Véase también reduceRight().

El método reduce() no reduce la matriz original.

Este ejemplo encuentra la suma de todos los números en una matriz:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);
  
function myFunction(total, value, index, array) {
  
  return total + value;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduce() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value, index, array) {
  return total + value;
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 4 argumentos:

  • El total (el valor inicial/valor devuelto previamente)

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí

El ejemplo anterior no utiliza los parámetros de índice y matriz. Puede ser reescrito a:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);
  
function myFunction(total, value) {
  
  return total + value;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduce() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value) {
  return total + value;
}
</script>

</body>
</html>

El método reduce() puede aceptar un valor inicial:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction, 
  100);
  
function myFunction(total, value) {
  return total + value;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduce() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction, 100);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value) {
  return total + value;
}
</script>

</body>
</html>

Matriz de JavaScript reduceRight()

El método reduceRight() ejecuta una función en cada elemento de la matriz para producir (reducirlo a) un único valor.

El reduceRight() funciona de derecha a izquierda en la matriz. Véase también reduce().

El método reduceRight() no reduce la matriz original.

Este ejemplo encuentra la suma de todos los números en una matriz:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);
  
function myFunction(total, value, index, array) {
  
  return total + value;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduceRight() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value, index, array) {
  return total + value;
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 4 argumentos:

  • El total (el valor inicial/valor devuelto previamente)

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí

El ejemplo anterior no utiliza los parámetros de índice y matriz. Puede ser reescrito a:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);
  
function myFunction(total, value) {
  return total + value;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduceRight() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value) {
  return total + value;
}
</script>

</body>
</html>

Matriz de JavaScript cada()

El método every() comprueba si todos los valores de la matriz pasan una prueba.

Este ejemplo comprueba si todos los valores de la matriz son mayores que 18:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let allOver18 = 
  numbers.every(myFunction);
function myFunction(value, index, array) {
    return 
  value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The every() Method</h2>

<p>The every() method checks if all array values pass a test.</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

document.getElementById("demo").innerHTML = "All over 18 is " + allOver18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 3 argumentos:

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí

Cuando una función de devolución de llamada usa solo el primer parámetro (valor), el otro Los parámetros se pueden omitir:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let allOver18 = 
  numbers.every(myFunction);
function myFunction(value) {
  return 
  value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The every() Method</h2>

<p>The every() method checks if all array values pass a test.</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

document.getElementById("demo").innerHTML = "All over 18 is " + allOver18;

function myFunction(value) {
  return value > 18;
}
</script>

</body>
</html>

Matriz de JavaScript algunos()

El método some() comprueba si algunos valores de la matriz pasan una prueba.

Este ejemplo comprueba si algunos valores de matriz son mayores que 18:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);
function myFunction(value, index, array) {
    return 
  value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The some() Method</h2>

<p>The some() method checks if some array values pass a test:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);

document.getElementById("demo").innerHTML = "Some over 18 is " + someOver18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 3 argumentos:

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí


Matriz de JavaScript indexOf()

El método indexOf() busca en una matriz un valor de elemento y devuelve su posición.

Nota: El primer elemento tiene la posición 0, el segundo elemento tiene la posición 1, y así sucesivamente.

Ejemplo

Busque en una matriz el elemento "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The indexOf() Method</h2>

<p id="demo"></p>

<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;

document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>

</body>
</html>

Sintaxis

array.indexOf(item, start)
item

Requerido. El elemento a buscar.

start

Opcional. Dónde empezar la búsqueda. Los valores negativos comenzarán en la posición dada contando desde el final y buscarán hasta el final.

Array.indexOf() devuelve -1 si no se encuentra el elemento.

Si el elemento está presente más de una vez, devuelve la posición del primero. ocurrencia.


Matriz de JavaScript lastIndexOf()

Array.lastIndexOf() es lo mismo que Array.indexOf(), pero devuelve la posición de la última aparición del elemento especificado.

Ejemplo

Busque en una matriz el elemento "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The lastIndexOf() Method</h2>

<p id="demo"></p>

<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;

document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>

</body>
</html>

Sintaxis

array.lastIndexOf(item, start)
item

Requerido. El elemento a buscar

start

Opcional. Dónde empezar la búsqueda. Los valores negativos comenzarán en la posición dada contando desde el final y buscarán hasta el principio.


Matriz de JavaScript buscar()

El método find() devuelve el valor del primer elemento de la matriz que pasa un función de prueba.

Este ejemplo encuentra (devuelve el valor de) el primer elemento que es más grande de 18:

Ejemplo

const numbers = [4, 9, 16, 25, 29];
let first = 
  numbers.find(myFunction);
function myFunction(value, index, array) {
  return 
  value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The find() Method</h2>

<p id="demo"></p>

<script>
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);

document.getElementById("demo").innerHTML = "First number over 18 is " + first;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 3 argumentos:

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí

Soporte del navegador

find() es una característica de ES6 (JavaScript 2015).

Es compatible con todos los navegadores modernos:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

find() no es compatible con Internet Explorer.


Matriz de JavaScript findIndex()

El método findIndex() devuelve el índice del primer elemento de la matriz que pasa una función de prueba.

Este ejemplo encuentra el índice del primer elemento mayor que 18:

Ejemplo

const numbers = [4, 9, 16, 25, 29];
let first = 
  numbers.findIndex(myFunction);
function myFunction(value, index, array) {
    return 
  value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The findIndex() Method</h2>

<p id="demo"></p>

<script>
const numbers = [4, 9, 16, 25, 29];

document.getElementById("demo").innerHTML = "First number over 18 has index " + numbers.findIndex(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Tenga en cuenta que la función toma 3 argumentos:

  • El valor del artículo

  • El índice de artículos

  • La matriz en sí

Soporte del navegador

findIndex() es una característica de ES6 (JavaScript 2015).

Es compatible con todos los navegadores modernos:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

findIndex() no es compatible con Internet Explorer.


JavaScript Array.from()

El método Array.from() devuelve un objeto Array de cualquier objeto con una longitud propiedad o cualquier objeto iterable.

Ejemplo

Cree una matriz a partir de una cadena:

Array.from("ABCDEFG");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The from() Method</h2>

<p>Return an array object from any object with a length property or any iterable object.</p>

<p id="demo"></p>

<script>
const myArr = Array.from("ABCDEFG");
document.getElementById("demo").innerHTML = myArr;
</script>

<p>The Array.from() method is not supported in Internet Explorer.</p>

</body>
</html>

Soporte del navegador

from() es una característica de ES6 (JavaScript 2015).

Es compatible con todos los navegadores modernos:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

from() no es compatible con Internet Explorer.


Matriz de JavaScript Claves()

El método Array.keys() devuelve un objeto Array Iterator con las claves de una matriz.

Ejemplo

Cree un objeto Array Iterator, que contenga las claves de la matriz:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();

for (let x of keys) {
  text += x + "<br>";
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The keys() Method</h2>

<p>Return an Array Iterator object with the keys of the array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();

let text = "";
for (let x of keys) {
  text += x + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

<p>Array.keys() is not supported in Internet Explorer.</p>

</body>
</html>

Soporte del navegador

keys() es una característica de ES6 (JavaScript 2015).

Es compatible con todos los navegadores modernos:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

keys() no es compatible con Internet Explorer.


Matriz de JavaScript entradas()

Ejemplo

Cree un iterador de matriz y luego repita los pares clave/valor:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();
for (let x of f) {
  document.getElementById("demo").innerHTML += x;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arrays</h1>
<h2>The entries() method</h2>

<p>entries() returns an Array Iterator object with key/value pairs:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();

for (let x of f) {
  document.getElementById("demo").innerHTML += x + "<br>";
}
</script>

<p>The entries() method is not supported in Internet Explorer 11 (or earlier).</p>

</body>
</html>

El método entries() devuelve un objeto Array Iterator con pares clave/valor:

[0, "Plátano"]
[1, "Naranja"]
[2, "Manzana"]
[3, "Mango"]

El método entries() no cambia la matriz original.

Soporte del navegador

entries() es una característica de ES6 (JavaScript 2015).

Es compatible con todos los navegadores modernos:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

entries() no es compatible con Internet Explorer.


Matriz de JavaScript incluye()

ECMAScript 2016 introdujo Array.includes() en las matrices. Esto nos permite verificar si un elemento está presente en una matriz (incluido NaN, a diferencia de indexOf).

Ejemplo

const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.includes("Mango"); // is true

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The includes() Method</h2>

<p>Check if the fruit array contains "Mango":</p>

<p id="demo"></p>

<p><strong>Note:</strong> The includes method is not supported in Edge 13 (and earlier versions).</p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.includes("Mango");
</script>

</body>
</html>

Sintaxis

array.includes(search-item)

Array.includes() permite comprobar los valores de NaN. A diferencia de Array.indexOf().

Soporte del navegador

includes() es una característica de ECMAScript 2016.

Es compatible con todos los navegadores modernos:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

includes() no es compatible con Internet Explorer.


Extensión de matriz de JavaScript (...)

El operador ... expande un iterable (como una matriz) en más elementos:

Ejemplo

const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];

const year = [...q1, ...q2, ...q3, ...q4];

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The ... Operator</h2>

<p>The "spread" operator spreads elements of iterable objects:</p>

<p id="demo"></p>

<script>
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];

const year = [...q1, ...q2, ...q3, ...q4];
document.getElementById("demo").innerHTML = year; 
</script>

</body>
</html>

Soporte del navegador

... es una característica de ES6 (JavaScript 2015).

Es compatible con todos los navegadores modernos:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

... no es compatible con Internet Explorer.


Referencia de matriz completa

Para obtener una referencia completa de Array, vaya a nuestro:

Referencia completa de matrices de JavaScript.

La referencia contiene descripciones y ejemplos de todos los Array. propiedades y métodos.