Práctica sobre métodos de array

Overview

Práctica de Arrays

Este es el repositorio de acompañamiento de este stream. Si querés saber más sobre Arrays podes visitar la MDN en su artículo de primeros pasos

Instrucciones para correr la aplicación

Podés correr la app desde codesandbox sin necesidad de instalar nada entrando a este link

Si querés correr este repositorio localmente podes clonarlo y luego correr:

npm install
npm run dev

Tareas

Implementá todos los métodos que tengan un @TODO

Intro a arrays

Los array sirven para almacenar listas.

const items = ['cámara', 'celular', 'reloj']

Esas listas pueden almacenar cualquier tipo de dato y no todos los elementos tienen por que ser del mismo tipo.

const weirdItems = ['cámara', 2, 'reloj']

Cualquier tipo, incluyendo otros arrays.

const extraWeirdItems = ['cámara', 2, 'reloj', [], ['por', 'que', '?']]

Podemos acceder a sus elementos por índice, los arrays inician desde el índice 0.

const numArray = ['cero', 'uno', 'dos']

numArray[1] // => 'uno'

Podemos modificar los elementos por índice también

numArray[1] = 'one'

numArray // => [ 'cero', 'one', 'dos' ]

Los arrays poseen numerosas propiedades y métodos que podemos usar para interactuar con ellos.

numArray.length // 3
numArray.forEach(num => console.log(`número: ${num}`)) // 'número: N'

Algunos de estos métodos suelen usarse para modificar u obtener copias del array, los métodos que modifican el array original se los llaman métodos mutables.

const mutableArray = [1, 2, 3]

// Agregar un elemento al final
mutableArray.push(4)

// Eliminar el primer elemento
mutableArray.shift()

mutableArray // [2, 3, 4]

Los métodos que devuelven una copia modificada sin modificar el array original, se los llama métodos inmutables.

const immutableArray = [1, 2, 3]

// Agregar un elemento al final
const concatenatedArray = immutableArray.concat(4)

// Eliminar el primer elemento
const shiftedArray = immutableArray.slice(1)

immutableArray // [1, 2, 3]
concatenatedArray // [1, 2, 3, 4]
shiftedArray // [2, 3]

La decisión de que métodos usar está en cada uno y en las necesidades que tengamos a la hora de manipular nuestros datos. En este ejercicio vamos a estar haciendo cambios a una aplicación React, donde se aconseja no debemos mutar los estados ya que esto puede interferir con el resultado esperado, por ende vamos a centrarnos en algunos de los métodos inmutables como .concat, .filter, .map, .reduce o .some.


Si te gusta mi contenido, seguime en Twitter, Twitch, YouTube, convertite en GitHub sponsor, votame para Github Star o doname un Cafecito

You might also like...

A simple module to get porperties of an array

A simple module to get statistical porperties of an array. Currently the possible properties are mean, stdev and variance.

Nov 29, 2022

🧰 Javascript array-like containers for multithreading

بسم الله الرحمن الرحيم Struct Vec 🧰 Javascript array-like containers for multithreading Efficiently communicating between js workers is a pain becaus

Jun 23, 2022

Useful for managing a wrapping index for an array of items.

use-wrapping-index Useful for managing a wrapping index for an array of items. Usage import useWrappingIndex from "@alexcarpenter/use-wrapping-index";

Dec 9, 2022

Converts an iterable, iterable of Promises, or async iterable into a Promise of an Array.

iterate-all A utility function that converts any of these: IterableT IterablePromiseT AsyncIterableT AsyncIterablePromiseT Into this: Prom

Jun 7, 2022

Small, typed, dependency free tool to round corners of 2d-polygon provided by an array of { x, y } points.

Small, typed, dependency free tool to round corners of 2d-polygon provided by an array of { x, y } points.

round-polygon Small, typed, dependency-free tool to round corners of 2d-polygon provided by an array of { x, y } points. The algorithm prevents roundi

Nov 26, 2022

we learn the whole concept of JS including Basics like Object, Functions, Array etc. And Advance JS - Understanding DOMs, JQuery, Ajax, Prototypes etc.

JavaScript-for-Complete-Web Development. we learn the whole concept of JS including Basics like Object, Functions, Array etc. And Advance JS - Underst

Jul 22, 2022

Fix for Object.keys, which normally just returns an array of strings, which is not good when you care about strong typing

Fix for Object.keys, which normally just returns an array of strings, which is not good when you care about strong typing

Welcome to ts-object-keys 👋 Fix for Object.keys, which normally just returns an array of strings, which is not good when you care about strong typing

Jul 4, 2022

An extension of the Map class with more Array-like features.

BetterMap An extension of the Map class with more Array-like features. Installation There ain't no installation. It's a Deno module. Usage import { Be

Oct 24, 2022

jsonrawtoxlsx is library to convert json raw (array) into xlsx file

jsonrawtoxlsx is library to convert json raw (array) into xlsx file

Welcome to jsonrawtoxlsx 👋 ✨ What is jsonrawtoxlsx? jsonrawtoxlsx is library to convert json raw (array) into xlsx file ⚡️ Installation using npm npm

Dec 23, 2022
Owner
Gonzalo Pozzo
Javascript developer, in ❤️ with React.
Gonzalo Pozzo
Diferentes demos em relação ao uso do Playwright para realização de palestras sobre o assunto

?? Playwright [Demos] - Palestra: Testes Inteligentes, Automatizados e Rápidos em Cross-Browser com Playwright! Repositório responsável pelas demos re

Glaucia Lemos 47 Oct 20, 2022
Agreador de info de libros sobre Desarrollo y Programación

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Carlos Azaustre 13 Feb 23, 2022
Projeto individual, um site para cobertura de partidas de vôlei, times onde você pode saber onde, quando acontecerá as partidas, e dados sobre os times.

?? Volleyball Esports Coverage Um portal de vôlei para as pessoas se conectarem ou divulgarem suas partidas, conhecimentos e uma maneira de conhecerem

PedroJsn 4 Jun 6, 2022
Repositorio sobre arrays con información y ejemplos.

Arrays Repositorio sobre arrays con información y ejemplos. 1)Para poder utilizar el repositorio correctamente es necesario que se eliminen los coment

EzequielJumilla 10 Sep 14, 2022
Repositorio del video de YouTube sobre creación y generación de imágenes de docker con Node

Importante Tener instalado Docker Desktop!!! Comandos usados Login de Docker Hub docker login Generar la imagen, especificar el TAG (-t) y el punto s

Fernando 5 Oct 27, 2022
Fundamentos, estruturas, função, objeto, array e etc...

JavaScript Fundamentos, estruturas, função, array e etc... Atividades praticas detalhadas e comentadas para todo mundo entender cada tag, bons estudos

Leonardo Madeira 6 Feb 27, 2022
Complete JavaScipt Array methods Cheatsheet 🚀

Javascript Array Cheatsheet ?? Click to download ☝ Important ?? There is no way this is perfect or include all the methods. I'll try to fix/add more m

Ayush 91 Dec 7, 2022
Draft specification for a proposed Array.fromAsync method in JavaScript.

Array.fromAsync for JavaScript ECMAScript Stage-1 Proposal. J. S. Choi, 2021. Specification available Polyfill available Why an Array.fromAsync method

Ecma TC39 126 Dec 14, 2022
Analisador de números utilizando Array JavaScript com Html 5 e CSS 3

Olá pessal, tudo bem? :D Esse site foi desenvolvido para analisar números armazenados em um array chamado "dados[]". Temos dois botões um input e uma

Yuri Willian 0 Jan 6, 2022
Hierarchical Converter for Array of Objects

Conversor Hierárquico para Array de Objetos - Hierarchical Converter to Array of Objects Docker-compose Cria a interface network e containers indicado

Victor Vinícius Eustáquio de Almeida 2 Jan 27, 2022