SlideShare una empresa de Scribd logo
concat()
every()
JavaScript
filter()
shift()
entries()
unshift()
reduce() find()
slice()
push()
S E P A R A R Y U N I R
map()
join()
split()
T R A N S F O R M A R
COMPROBACIONES
some()
B Ú S Q U E D A
findIndex()
findLast()
findLastIndex()
A C U M U L A D O R E S
reduceRight()
F I L T R O S
A Ñ A D I R
E L I M I N A R
E X T R A E R
pop()
JavaScript
Array.isArray()
E S T A T I C O S
Array.of()
JS
El método estático Array.isArray() verifica si el argumento pasado es una
matriz o no.
$ node index.js
TERMINAL
true
false
const numbers = [1, 2, 3, 4];
console.log(Array.isArray(numbers));
const text = "JavaScript";
console.log(Array.isArray(text));
index.js
JS
El método Array.of() crea una instancia de Array (la diferencia con el
constructor es como maneja los parámetros de tipo entero).
$ node index.js
TERMINAL
[7]
[1, 2, 3]
[undefined, undefined,
undefined, undefined,
undefined, undefined,
undefined]
[1, 2, 3]
const arr1 = Array.of(7);
console.log(arr1);
const arr2 = Array.of(1, 2, 3);
console.log(arr2);
const arr3 = Array(7);
console.log(arr3);
const arr4 = Array(1, 2, 3);
console.log(arr4);
index.js
JS
El método .concat() devuelve la unión de dos o más matrices
(no modifica las matrices involucradas).
$ node index.js
TERMINAL
"superman"
"aquaman"
"batman"
"flash"
"deadpool"
"hulk"
"wolverine"
"ironman"
const heroesDC = [
"superman", "aquaman", "batman","flash"
];
const heroesMarvel = [
"deadpool", "hulk", "wolverine", "ironman"
];
const multiverso = heroesDC.concat(
heroesMarvel);
multiverso.forEach(heroe => {
console.log(heroe)
});
index.js
index.js
El método .every() devuelve true si todos los elementos cumplen la
condición en la función.
$ node index.js
TERMINAL
false
true
const arrNumbers1 = [10, 20, 55.33, 23];
const arrNumbers2 = [2, 4, 6, 8, 10, 12];
function numberIsEven(num) {
return Math.round(num) % 2 === 0;
}
console.log(arrNumbers1.every(numberIsEven)
);
console.log(arrNumbers2.every(numberIsEven)
);
JS
index.js
$ node index.js
TERMINAL
const numbers = [10, 20, 55.33, 23];
const n = numbers.entries(num);
for (let x of n) {
console.log(x);
}
El método .entries() devuelve un objeto [Array Iterator] con pares
clave/valor
[0, 10]
[1, 20]
[2, 55.33]
[3, 23]
JS
index.js
El método .filter() crea una nueva matriz con los elementos que
cumplen una condición.
$ node index.js
TERMINAL
const numbers = [10, 20, 55.33, 23];
function numberIsEven(num) {
return Math.round(num) % 2 === 0;
}
const pares = numbers.filter(numberIsEven);
console.log(pares);
[10, 20]
JS
index.js
$ node index.js
TERMINAL
const heroes = [
"superman",
"aquaman",
"batman",
"ironman"
];
const batman = heroes.find(hero => {
return hero === "batman"
});
console.log(batman);
El método .find() devuelve el valor del primer elemento que cumple
una condición.
"batman"
JS
index.js
$ node index.js
TERMINAL
const heroes = [
"superman",
"aquaman",
"batman",
"ironman",
"batwoman"
];
const heroe = heroes.findLast(hero => {
return hero.startsWith("b");
});
console.log(heroe);
El método .findLast() devuelve el valor del elemento que cumple una
condición, pero buscando elementos desde derecha a izquierda.
"batwoman"
JS
index.js
$ node index.js
TERMINAL
const heroes = [
"superman",
"aquaman",
"batman",
"ironman"
];
const index = heroes.findIndex(hero => {
return hero === "batman"
});
console.log(index);
El método .findIndex() devuelve el valor de la posición en la matriz
del primer elemento que cumple una condición.
2
JS
index.js
$ node index.js
TERMINAL
const heroes = [
"superman",
"aquaman",
"batman",
"ironman",
"batwoman"
];
const index = heroes.findLastIndex(hero => {
return hero.startsWith("b");
});
console.log(index);
El método .findIndexLast() devuelve el valor de la posición en la matriz del
elemento que cumple una condición, pero buscando desde derecha a izquierda.
4
JS
index.js
$ node index.js
TERMINAL
const numbers = [10, 20, 55.33, 23];
numbers.shift();
numbers.forEach((num, index) => {
console.log(`${index}, ${num}`)
});
El método .shift() elimina el primer elemento de la matriz y cambia
todos los demás elementos a un índice más bajo.
"0, 20"
"1, 55.33"
"2, 34"
JS
index.js
El método .some() devuelve true si al menos uno de los elementos
cumplen la condición en la función callback.
$ node index.js
TERMINAL
true
false
const arrNumbers1 = [10, 20, 55.33, 23];
const arrNumbers2 = [1, 3, 5, 9, 11, 13];
function numberIsEven(num) {
return Math.round(num) % 2 === 0;
}
console.log(arrNumbers1.some(numberIsEven));
console.log(arrNumbers2.some(numberIsEven));
JS
index.js
$ node index.js
TERMINAL
const heroes = [
"superman",
"aquaman",
"batman",
"ironman"
];
heroes.unshift("flash", "spider-man");
heroes.forEach(heroe => {
console.log(heroe)
});
El método .unshif() agrega nuevos elementos al comienzo de la matriz
(sobrescribe la original).
JS
"flash"
"spider-man"
"superman"
"aquaman"
"batman"
"ironman"
index.js
$ node index.js
TERMINAL
const heroes = [
"superman",
"aquaman",
"batman",
"ironman"
]
heroes.sort()
.forEach(heroe => {
console.log(heroe)
});
El método .sort() ordena los elementos como cadenas en orden
alfabético y ascendente
JS
"aquaman"
"batman"
"ironman"
"superman"
index.js
$ node index.js
TERMINAL
const numbers = [10, 20, 55.33, 23];
function getSum(total, num) {
return total + Math.round(num);
}
const total = numbers.reduce(getSum, 0);
console.log(total);
El método .reduce() devuelve un único valor; el resultado acumulado
de la función reductora.
JS
108
index.js
$ node index.js
TERMINAL
const numbers = [95, 5, 25, 10, 25];
const result = numbers.reduceRight((first, second) => {
console.log(`F=${first} S=${second}`);
return first - second;
});
console.log(result);
El método .reduceRight() devuelve un único valor; el resultado acumulado de la
función reductora (acumulando el valor de derecha a izquierda).
JS
"F=25 S=10"
"F=15 S=25"
"F=-10 S=5"
"F=-15 S=95"
- 110
index.js
$ node index.js
TERMINAL
const heroesDC = [
"batgirl",
"green arrow",
"catwoman",
"shazam"
];
console.log(heroesDC.pop());
heroesDC.forEach(hero =>
console.log(hero));
El método .pop elimina un elemento de la matriz
(el del final, devuelve el elemento eliminado).
"shazam"
"batgirl"
"green arrow"
"catwoman"
JS
index.js
$ node index.js
TERMINAL
const heroesDC = [
"batgirl",
"green arrow",
"catwoman",
"shazam"
];
heroesDC.push("literna verde",
"mujer maravilla");
heroesDC.forEach(hero =>
console.log(hero));
El método .push() agrega un nuevo elemento a una matriz
(al final, sobrescribe la original).
"batgirl"
"green arrow"
"catwoman"
"shazam"
"literna verde"
"mujer maravilla"
JS
index.js
$ node index.js
TERMINAL
const heroesDC = [
"batgirl",
"green arrow",
"catwoman",
"shazam"
];
heroesDC.splice(2, 1,
"literna verde", "mujer maravilla")
heroesDC.forEach(hero =>
console.log(hero));
El método .splice() se utiliza para agregar nuevos elementos a una
matriz (indicando su posición y cantidad de elementos a eliminar)
(modifica la matriz original).
JS
"batgirl"
"green arrow"
"literna verde"
"mujer maravilla"
"shazam"
index.js
$ node index.js
TERMINAL
const heroes = [
"batgirl",
"green arrow",
"catwoman",
"shazam",
"capitán américa",
"iron man",
"batman"
];
const heroesMarvel = heroes.slice(4, 6);
heroesMarvel.forEach(hero =>
console.log(hero));
El método .slice() se utiliza para extraer parte de una matriz, toma
dos argumentos la posición de un elemento de inicio y hasta un
elemento final (no incluye el elemento final).
JS
"capitán américa"
"iron man"
index.js
$ node index.js
TERMINAL
const heroes = [
"batgirl",
"green arrow",
"catwoman",
"shazam",
"capitán américa",
"iron man",
"batman"
];
const longitudNombres = heroes.map((nombre) =>
nombre.length
);
for (let n of longitudNombres) {
console.log(parseInt(n));
}
El método .map() se utiliza para transformar una matriz, llama una función una
vez para cada elemento de la matriz y así crea una matriz nueva
(no modifica la matriz original, no ejecuta la función en elementos vacíos).
JS
7
11
8
6
15
8
6
index.js
$ node index.js
TERMINAL
const letras = ["a","b","c","d"];
const unidosPorPunto = letras.join(".");
const unidosPorFlecha = letras.join("->");
console.log(unidosPorPunto);
console.log(unidosPorFlecha);
El método .join() se utiliza para crear un string con todos los elementos de
una matriz, uniéndolo por el texto que le pasemos por parámetro.
JS
"a.b.c.d"
"a->b->c->d"
index.js
$ node index.js
TERMINAL
const splitLetras = "a.b.c".split(".");
const splitDigitos = "5-4-3-2-1".split("-");
console.log(splitLetras);
console.log(splitDigitos);
El método .split() de un string es posible crear una matriz, separándolo por
el texto que le pasemos por parámetro (separador).
JS
["a", "b", "c"]
["5", "4", "3", "2", "1"]

Más contenido relacionado

La actualidad más candente

Redis Overview
Redis OverviewRedis Overview
Redis Overview
Hoang Long
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
kamal kotecha
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Unirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http ClientUnirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http Client
rahul patel
 
Introduction to cassandra
Introduction to cassandraIntroduction to cassandra
Introduction to cassandra
Nguyen Quang
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
MongoDB
 
Spark - Alexis Seigneurin (Français)
Spark - Alexis Seigneurin (Français)Spark - Alexis Seigneurin (Français)
Spark - Alexis Seigneurin (Français)
Alexis Seigneurin
 
Spring cloud on kubernetes
Spring cloud on kubernetesSpring cloud on kubernetes
Spring cloud on kubernetes
SangSun Park
 
Active MQ
Active MQActive MQ
Active MQ
Kris Jeong
 
Redis and it's data types
Redis and it's data typesRedis and it's data types
Redis and it's data types
Aniruddha Chakrabarti
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query OptimizationMongoDB
 
Decision Tree - C4.5&CART
Decision Tree - C4.5&CARTDecision Tree - C4.5&CART
Decision Tree - C4.5&CARTXueping Peng
 
Integrating Xtext Language Server support in Visual Studio Code
Integrating Xtext Language Server support in Visual Studio CodeIntegrating Xtext Language Server support in Visual Studio Code
Integrating Xtext Language Server support in Visual Studio Code
Karsten Thoms
 
Introduction to Sharding
Introduction to ShardingIntroduction to Sharding
Introduction to ShardingMongoDB
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
Data Exploration in R.pptx
Data Exploration in R.pptxData Exploration in R.pptx
Data Exploration in R.pptx
Ramakrishna Reddy Bijjam
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
Sunghyouk Bae
 
[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩
NHN FORWARD
 
jQuery
jQueryjQuery

La actualidad más candente (20)

Redis Overview
Redis OverviewRedis Overview
Redis Overview
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Exception handling
Exception handlingException handling
Exception handling
 
Unirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http ClientUnirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http Client
 
Introduction to cassandra
Introduction to cassandraIntroduction to cassandra
Introduction to cassandra
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
 
Spark - Alexis Seigneurin (Français)
Spark - Alexis Seigneurin (Français)Spark - Alexis Seigneurin (Français)
Spark - Alexis Seigneurin (Français)
 
Spring cloud on kubernetes
Spring cloud on kubernetesSpring cloud on kubernetes
Spring cloud on kubernetes
 
Active MQ
Active MQActive MQ
Active MQ
 
Redis and it's data types
Redis and it's data typesRedis and it's data types
Redis and it's data types
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 
Decision Tree - C4.5&CART
Decision Tree - C4.5&CARTDecision Tree - C4.5&CART
Decision Tree - C4.5&CART
 
Integrating Xtext Language Server support in Visual Studio Code
Integrating Xtext Language Server support in Visual Studio CodeIntegrating Xtext Language Server support in Visual Studio Code
Integrating Xtext Language Server support in Visual Studio Code
 
Introduction to Sharding
Introduction to ShardingIntroduction to Sharding
Introduction to Sharding
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
Data Exploration in R.pptx
Data Exploration in R.pptxData Exploration in R.pptx
Data Exploration in R.pptx
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
 
[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩
 
jQuery
jQueryjQuery
jQuery
 

Similar a js-arrays.pptx

Clase 7 objetos globales de javaScript
Clase 7 objetos globales de javaScriptClase 7 objetos globales de javaScript
Clase 7 objetos globales de javaScript
José Ricardo Tillero Giménez
 
Resultset
ResultsetResultset
Base datos mysql y visual basic
Base datos mysql y visual basicBase datos mysql y visual basic
Base datos mysql y visual basic
Rafael Tobar Jame
 
Funciones de visual basic
Funciones de visual basicFunciones de visual basic
Funciones de visual basic
BabyPerri
 
Funciones basicas
Funciones basicasFunciones basicas
Funciones basicas
FREDY CAÑAR
 
Taller de repaso de metodos y arreglos
Taller de repaso de metodos y arreglosTaller de repaso de metodos y arreglos
Taller de repaso de metodos y arreglosDiroplan
 
Vector
Vector Vector
clase 7 GRAFICOS 2D.pdf
clase 7 GRAFICOS 2D.pdfclase 7 GRAFICOS 2D.pdf
clase 7 GRAFICOS 2D.pdf
NandoMartiHufer
 
Java::Acceso a Bases de Datos
Java::Acceso a Bases de DatosJava::Acceso a Bases de Datos
Java::Acceso a Bases de Datosjubacalo
 
Separata java script
Separata java scriptSeparata java script
Separata java script
Carlos Enrique Huamán Solis
 
javascript2.ppt
javascript2.pptjavascript2.ppt
javascript2.ppt
DavidAguilera59
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
Paradigma Digital
 

Similar a js-arrays.pptx (20)

Clase 7 objetos globales de javaScript
Clase 7 objetos globales de javaScriptClase 7 objetos globales de javaScript
Clase 7 objetos globales de javaScript
 
Resultset
ResultsetResultset
Resultset
 
Ejemplos java
Ejemplos javaEjemplos java
Ejemplos java
 
Base datos mysql y visual basic
Base datos mysql y visual basicBase datos mysql y visual basic
Base datos mysql y visual basic
 
Comandos
ComandosComandos
Comandos
 
Comandos r
Comandos rComandos r
Comandos r
 
Funciones de visual basic
Funciones de visual basicFunciones de visual basic
Funciones de visual basic
 
Arreglos, Procedimientos y Funciones
Arreglos, Procedimientos y FuncionesArreglos, Procedimientos y Funciones
Arreglos, Procedimientos y Funciones
 
Funciones basicas
Funciones basicasFunciones basicas
Funciones basicas
 
Codigo ejercicios
Codigo ejerciciosCodigo ejercicios
Codigo ejercicios
 
Taller de repaso de metodos y arreglos
Taller de repaso de metodos y arreglosTaller de repaso de metodos y arreglos
Taller de repaso de metodos y arreglos
 
Vector
Vector Vector
Vector
 
clase 7 GRAFICOS 2D.pdf
clase 7 GRAFICOS 2D.pdfclase 7 GRAFICOS 2D.pdf
clase 7 GRAFICOS 2D.pdf
 
Presentacion
PresentacionPresentacion
Presentacion
 
Java::Acceso a Bases de Datos
Java::Acceso a Bases de DatosJava::Acceso a Bases de Datos
Java::Acceso a Bases de Datos
 
Netsbeans
NetsbeansNetsbeans
Netsbeans
 
Separata java script
Separata java scriptSeparata java script
Separata java script
 
javascript2.ppt
javascript2.pptjavascript2.ppt
javascript2.ppt
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Guia 3
Guia 3Guia 3
Guia 3
 

js-arrays.pptx

  • 1. concat() every() JavaScript filter() shift() entries() unshift() reduce() find() slice() push() S E P A R A R Y U N I R map() join() split() T R A N S F O R M A R COMPROBACIONES some() B Ú S Q U E D A findIndex() findLast() findLastIndex() A C U M U L A D O R E S reduceRight() F I L T R O S A Ñ A D I R E L I M I N A R E X T R A E R pop()
  • 2. JavaScript Array.isArray() E S T A T I C O S Array.of()
  • 3. JS El método estático Array.isArray() verifica si el argumento pasado es una matriz o no. $ node index.js TERMINAL true false const numbers = [1, 2, 3, 4]; console.log(Array.isArray(numbers)); const text = "JavaScript"; console.log(Array.isArray(text)); index.js
  • 4. JS El método Array.of() crea una instancia de Array (la diferencia con el constructor es como maneja los parámetros de tipo entero). $ node index.js TERMINAL [7] [1, 2, 3] [undefined, undefined, undefined, undefined, undefined, undefined, undefined] [1, 2, 3] const arr1 = Array.of(7); console.log(arr1); const arr2 = Array.of(1, 2, 3); console.log(arr2); const arr3 = Array(7); console.log(arr3); const arr4 = Array(1, 2, 3); console.log(arr4); index.js
  • 5. JS El método .concat() devuelve la unión de dos o más matrices (no modifica las matrices involucradas). $ node index.js TERMINAL "superman" "aquaman" "batman" "flash" "deadpool" "hulk" "wolverine" "ironman" const heroesDC = [ "superman", "aquaman", "batman","flash" ]; const heroesMarvel = [ "deadpool", "hulk", "wolverine", "ironman" ]; const multiverso = heroesDC.concat( heroesMarvel); multiverso.forEach(heroe => { console.log(heroe) }); index.js
  • 6. index.js El método .every() devuelve true si todos los elementos cumplen la condición en la función. $ node index.js TERMINAL false true const arrNumbers1 = [10, 20, 55.33, 23]; const arrNumbers2 = [2, 4, 6, 8, 10, 12]; function numberIsEven(num) { return Math.round(num) % 2 === 0; } console.log(arrNumbers1.every(numberIsEven) ); console.log(arrNumbers2.every(numberIsEven) ); JS
  • 7. index.js $ node index.js TERMINAL const numbers = [10, 20, 55.33, 23]; const n = numbers.entries(num); for (let x of n) { console.log(x); } El método .entries() devuelve un objeto [Array Iterator] con pares clave/valor [0, 10] [1, 20] [2, 55.33] [3, 23] JS
  • 8. index.js El método .filter() crea una nueva matriz con los elementos que cumplen una condición. $ node index.js TERMINAL const numbers = [10, 20, 55.33, 23]; function numberIsEven(num) { return Math.round(num) % 2 === 0; } const pares = numbers.filter(numberIsEven); console.log(pares); [10, 20] JS
  • 9. index.js $ node index.js TERMINAL const heroes = [ "superman", "aquaman", "batman", "ironman" ]; const batman = heroes.find(hero => { return hero === "batman" }); console.log(batman); El método .find() devuelve el valor del primer elemento que cumple una condición. "batman" JS
  • 10. index.js $ node index.js TERMINAL const heroes = [ "superman", "aquaman", "batman", "ironman", "batwoman" ]; const heroe = heroes.findLast(hero => { return hero.startsWith("b"); }); console.log(heroe); El método .findLast() devuelve el valor del elemento que cumple una condición, pero buscando elementos desde derecha a izquierda. "batwoman" JS
  • 11. index.js $ node index.js TERMINAL const heroes = [ "superman", "aquaman", "batman", "ironman" ]; const index = heroes.findIndex(hero => { return hero === "batman" }); console.log(index); El método .findIndex() devuelve el valor de la posición en la matriz del primer elemento que cumple una condición. 2 JS
  • 12. index.js $ node index.js TERMINAL const heroes = [ "superman", "aquaman", "batman", "ironman", "batwoman" ]; const index = heroes.findLastIndex(hero => { return hero.startsWith("b"); }); console.log(index); El método .findIndexLast() devuelve el valor de la posición en la matriz del elemento que cumple una condición, pero buscando desde derecha a izquierda. 4 JS
  • 13. index.js $ node index.js TERMINAL const numbers = [10, 20, 55.33, 23]; numbers.shift(); numbers.forEach((num, index) => { console.log(`${index}, ${num}`) }); El método .shift() elimina el primer elemento de la matriz y cambia todos los demás elementos a un índice más bajo. "0, 20" "1, 55.33" "2, 34" JS
  • 14. index.js El método .some() devuelve true si al menos uno de los elementos cumplen la condición en la función callback. $ node index.js TERMINAL true false const arrNumbers1 = [10, 20, 55.33, 23]; const arrNumbers2 = [1, 3, 5, 9, 11, 13]; function numberIsEven(num) { return Math.round(num) % 2 === 0; } console.log(arrNumbers1.some(numberIsEven)); console.log(arrNumbers2.some(numberIsEven)); JS
  • 15. index.js $ node index.js TERMINAL const heroes = [ "superman", "aquaman", "batman", "ironman" ]; heroes.unshift("flash", "spider-man"); heroes.forEach(heroe => { console.log(heroe) }); El método .unshif() agrega nuevos elementos al comienzo de la matriz (sobrescribe la original). JS "flash" "spider-man" "superman" "aquaman" "batman" "ironman"
  • 16. index.js $ node index.js TERMINAL const heroes = [ "superman", "aquaman", "batman", "ironman" ] heroes.sort() .forEach(heroe => { console.log(heroe) }); El método .sort() ordena los elementos como cadenas en orden alfabético y ascendente JS "aquaman" "batman" "ironman" "superman"
  • 17. index.js $ node index.js TERMINAL const numbers = [10, 20, 55.33, 23]; function getSum(total, num) { return total + Math.round(num); } const total = numbers.reduce(getSum, 0); console.log(total); El método .reduce() devuelve un único valor; el resultado acumulado de la función reductora. JS 108
  • 18. index.js $ node index.js TERMINAL const numbers = [95, 5, 25, 10, 25]; const result = numbers.reduceRight((first, second) => { console.log(`F=${first} S=${second}`); return first - second; }); console.log(result); El método .reduceRight() devuelve un único valor; el resultado acumulado de la función reductora (acumulando el valor de derecha a izquierda). JS "F=25 S=10" "F=15 S=25" "F=-10 S=5" "F=-15 S=95" - 110
  • 19. index.js $ node index.js TERMINAL const heroesDC = [ "batgirl", "green arrow", "catwoman", "shazam" ]; console.log(heroesDC.pop()); heroesDC.forEach(hero => console.log(hero)); El método .pop elimina un elemento de la matriz (el del final, devuelve el elemento eliminado). "shazam" "batgirl" "green arrow" "catwoman" JS
  • 20. index.js $ node index.js TERMINAL const heroesDC = [ "batgirl", "green arrow", "catwoman", "shazam" ]; heroesDC.push("literna verde", "mujer maravilla"); heroesDC.forEach(hero => console.log(hero)); El método .push() agrega un nuevo elemento a una matriz (al final, sobrescribe la original). "batgirl" "green arrow" "catwoman" "shazam" "literna verde" "mujer maravilla" JS
  • 21. index.js $ node index.js TERMINAL const heroesDC = [ "batgirl", "green arrow", "catwoman", "shazam" ]; heroesDC.splice(2, 1, "literna verde", "mujer maravilla") heroesDC.forEach(hero => console.log(hero)); El método .splice() se utiliza para agregar nuevos elementos a una matriz (indicando su posición y cantidad de elementos a eliminar) (modifica la matriz original). JS "batgirl" "green arrow" "literna verde" "mujer maravilla" "shazam"
  • 22. index.js $ node index.js TERMINAL const heroes = [ "batgirl", "green arrow", "catwoman", "shazam", "capitán américa", "iron man", "batman" ]; const heroesMarvel = heroes.slice(4, 6); heroesMarvel.forEach(hero => console.log(hero)); El método .slice() se utiliza para extraer parte de una matriz, toma dos argumentos la posición de un elemento de inicio y hasta un elemento final (no incluye el elemento final). JS "capitán américa" "iron man"
  • 23. index.js $ node index.js TERMINAL const heroes = [ "batgirl", "green arrow", "catwoman", "shazam", "capitán américa", "iron man", "batman" ]; const longitudNombres = heroes.map((nombre) => nombre.length ); for (let n of longitudNombres) { console.log(parseInt(n)); } El método .map() se utiliza para transformar una matriz, llama una función una vez para cada elemento de la matriz y así crea una matriz nueva (no modifica la matriz original, no ejecuta la función en elementos vacíos). JS 7 11 8 6 15 8 6
  • 24. index.js $ node index.js TERMINAL const letras = ["a","b","c","d"]; const unidosPorPunto = letras.join("."); const unidosPorFlecha = letras.join("->"); console.log(unidosPorPunto); console.log(unidosPorFlecha); El método .join() se utiliza para crear un string con todos los elementos de una matriz, uniéndolo por el texto que le pasemos por parámetro. JS "a.b.c.d" "a->b->c->d"
  • 25. index.js $ node index.js TERMINAL const splitLetras = "a.b.c".split("."); const splitDigitos = "5-4-3-2-1".split("-"); console.log(splitLetras); console.log(splitDigitos); El método .split() de un string es posible crear una matriz, separándolo por el texto que le pasemos por parámetro (separador). JS ["a", "b", "c"] ["5", "4", "3", "2", "1"]