Arrays
Arrays Fundamental
Section titled “Arrays ”Creación y acceso Básico
Section titled “Creación y acceso ”Crear arrays
Section titled “Crear arrays”// Array literalconst frutas = ['manzana', 'banana', 'naranja'];
// Constructor Arrayconst numeros = new Array(1, 2, 3, 4, 5);
// Array vacíoconst vacio = [];
// Array con diferentes tipos de datosconst mixto = [1, 'texto', true, { nombre: 'Juan' }, [1, 2, 3]];Acceso a elementos
Section titled “Acceso a elementos”const frutas = ['manzana', 'banana', 'naranja'];
// Acceso por índiceconsole.log(frutas[0]); // 'manzana'
// Último elementoconsole.log(frutas[frutas.length - 1]); // 'naranja'
// Índice fuera de rangoconsole.log(frutas[10]); // undefinedMétodos básicos Importante
Section titled “Métodos básicos ”Agregar y eliminar elementos
Section titled “Agregar y eliminar elementos”const frutas = ['manzana', 'banana'];
// Agregar al finalfrutas.push('naranja'); // ['manzana', 'banana', 'naranja']
// Eliminar del finalfrutas.pop(); // ['manzana', 'banana']
// Agregar al iniciofrutas.unshift('fresa'); // ['fresa', 'manzana', 'banana']
// Eliminar del iniciofrutas.shift(); // ['manzana', 'banana']
// Eliminar/agregar en cualquier posiciónfrutas.splice(1, 1, 'kiwi'); // ['manzana', 'kiwi']Métodos de orden superior Avanzado
Section titled “Métodos de orden superior ”const numeros = [1, 2, 3, 4];const duplicados = numeros.map(num => num * 2);// [2, 4, 6, 8]filter
Section titled “filter”const numeros = [1, 2, 3, 4, 5, 6];const pares = numeros.filter(num => num % 2 === 0);// [2, 4, 6]reduce
Section titled “reduce”const numeros = [1, 2, 3, 4];const suma = numeros.reduce((total, num) => total + num, 0);// 10forEach
Section titled “forEach”const frutas = ['manzana', 'banana', 'naranja'];frutas.forEach((fruta, index) => { console.log(`${index}: ${fruta}`);});Desestructuración de arrays Moderno
Section titled “Desestructuración de arrays ”// Desestructuración básicaconst [primero, segundo] = [1, 2, 3];console.log(primero); // 1console.log(segundo); // 2
// Omitir elementosconst [a, , c] = [1, 2, 3];console.log(a, c); // 1, 3
// Con rest operatorconst [head, ...tail] = [1, 2, 3, 4];console.log(head); // 1console.log(tail); // [2, 3, 4]
// Valores por defectoconst [x = 1, y = 2] = [];console.log(x, y); // 1, 2Métodos útiles adicionales Complementario
Section titled “Métodos útiles adicionales ”Búsqueda y comprobación
Section titled “Búsqueda y comprobación”const numeros = [1, 2, 3, 4, 5];
// Encontrar un elementonumeros.find(num => num > 3); // 4
// Comprobar si existenumeros.includes(3); // true
// Encontrar índicenumeros.indexOf(3); // 2
// Comprobar si alguno cumplenumeros.some(num => num > 4); // true
// Comprobar si todos cumplennumeros.every(num => num > 0); // trueOrdenación y manipulación
Section titled “Ordenación y manipulación”const letras = ['c', 'a', 'b'];
// Ordenarletras.sort(); // ['a', 'b', 'c']
// Invertirletras.reverse(); // ['c', 'b', 'a']
// Unir arraysconst array1 = [1, 2];const array2 = [3, 4];const unidos = [...array1, ...array2]; // [1, 2, 3, 4]Mejores prácticas Recomendado
Section titled “Mejores prácticas ”Usar métodos inmutables cuando sea posible
Section titled “Usar métodos inmutables cuando sea posible”// ❌ Maloconst numeros = [1, 2, 3];numeros.push(4);
// ✅ Buenoconst numeros = [1, 2, 3];const nuevosNumeros = [...numeros, 4];Evitar modificar arrays en bucles
Section titled “Evitar modificar arrays en bucles”// ❌ Maloconst array = [1, 2, 3];for(let i = 0; i < array.length; i++) { array[i] = array[i] * 2;}
// ✅ Buenoconst array = [1, 2, 3];const resultado = array.map(num => num * 2);
🐝