6. Array
There is a variable that can hold more than one value. Technically, it's a data structure that can hold a collection of values. In other words, a variable that stores a list of other variables. This feature is called: array.
Create
An empty array called semana.
// Empty
const semana = [];
Below you can see an array filled with the days of the week.
// Filled
const semana = ['lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado', 'domingo'];
Read
To get a value from the array you must use its position wrapped in square brackets [] or the at function. Counting starts at 0.
const semana = ['lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado', 'domingo'];
console.log(semana[0]);
// lunes
console.log(semana.at(0));
// lunes
If I want the second one, I'll use 1.
console.log(semana[1]);
// martes
console.log(semana.at(1));
// martes
You can even capture values using negative indexes, although only with at. Suppose you want to get the last element of the array but don't know its length.
console.log(semana.at(-1));
// domingo
And the second to last?
console.log(semana.at(-2));
// sábado
Length
You must use the length variable, found inside the array.
console.log(semana.length);
// 7
Add
You can concatenate the array with a new value, saving the result in a new variable or overwriting the original array.
const dosMeses = meses.concat("Febrero");
console.log(dosMeses);
// ["Enero", "Febrero"]
console.log(meses);
// ["Enero"]
Another option is to modify the array with the push() function.
let meses = ["Enero"];
meses.push("Febrero");
// 2
console.log(meses);
// ["Enero", "Febrero"]
It will return the length of the array.
Which one should you use? It depends on whether you work by mutating (modifying) variables or not.
Remove
First element
One strategy is to create a new array without the first element. For this we can use slice(1), which will clone from the position we want. In this case, from the first one onward.
const semana = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"];
const semanaSinLunes = meses.slice(1);
// ["martes", "miércoles", "jueves", "viernes", "sábado", "domingo"]
Another possibility is mutating the array with shift().
let semana = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"];
semana.shift();
console.log(semana);
// ["martes", "miércoles", "jueves", "viernes", "sábado", "domingo"]
Last element
We can use slice again. In this case we'll clone from position 0 to the second to last (-1 or semana.length - 1).
const semana = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"];
const semanaSinDomingo = semana.slice(0, -1);
console.log(semanaSinDomingo);
// ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"]
If you want to modify the array, we can use pop().
let semana = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"];
semana.pop();
console.log(semana);
// ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"]
Specific position
In the examples we'll remove sábado, which occupies position 5.
Without modifying the original array we can filter it with filter.
const semana = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"];
const semanaSinSabado = semana.filter(function (valor, posicion) {
return posicion !== 5
});
console.log(semanaSinSabado);
// ["lunes", "martes", "miércoles", "jueves", "viernes", "domingo"]
If we want to modify the array, we have splice (not to be confused with slice). The first argument is the position and the second is the number of elements to remove (in the example it will be 1).
let semana = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"];
semana.splice(5, 1);
console.log(semana);
// ["lunes", "martes", "miércoles", "jueves", "viernes", "domingo]
Advanced
Transformation, Conversion, and Checking Functions
There is a set of functions that will be very helpful for managing arrays.
- filter
- reduce
- map
- fill
- find
- includes, checks whether an element exists inside an
array. - some, tells you whether an
arraymeets the condition at some point. - every, same as
somebut it must always be met. - forEach, iterates over an
array, getting its position and value.
You can read a summary in the following article on functional JavaScript.
Set (Sets)
To avoid duplicates inside an array you can use a tool built for that purpose, the Set() object. Its purpose isn't to replace the array but to avoid duplicates when adding new values and to tell you whether one already exists. Nothing more!
Create
Use new Set().
let setPelis = new Set();
Or start with values from an array.
let setPelis = new Set(["Lo que el viento se llevó", "La gran evasión"]);
Read
There's no point in reading it, since its purpose is to tell you whether an element already exists or to avoid duplicates, not to retrieve values by index.
Length
Use the size value.
let setPelis = new Set(["Lo que el viento se llevó", "La gran evasión"]);
console.log(setPelis.size)
// 2
Add
We have a function called add().
let setPelis = new Set();
setPelis.add("Lo que el viento se llevó")
setPelis.add("Lo que el viento se llevó")
setPelis.add("La gran evasion")
console.log(setPelis)
// ["Lo que el viento se llevó", "La gran evasión"]
Check if it exists
You can use has() with the value you want to check as its input parameter.
let setPelis = new Set(["Lo que el viento se llevó", "La gran evasión"]);
console.log(setPelis.has("La gran evasion"))
// true
Remove
You can remove values using delete(), indicating as the input parameter what you want to remove.
let setPelis = new Set(["Lo que el viento se llevó", "La gran evasión"]);
setPelis.delete("La gran evasión");
console.log(setPelis)
// ["Lo que el viento se llevó"]
Activity 1
Create an array with products and print them to the console.
Activity 2
Calculate the average of the following grades
const notas_1 = [1, 7, 3];
const notas_2 = [9, 6, 2];
Activity 3
Given the following array.
const lista_numeros = [2, 1, 6, 7, 6, 3];
- Add up all the numbers.
- Print a random number from the list.
- Remove the first number.
- Remove the last number.
- Add them up again.
- Add a 5.
- Add them up again.
Activity 4
Remove, or create a new array of, all the domains that don't contain the letter h.
const lista_dominios = ["hbo.com", "bbc.uk", "ebay.com", "hulu.com", "reddit.com", "adobe.es", "google.com", "huffingtonpost.com"];
Activity 5
Create a function that returns clues about a word to guess.
The rules will be as follows.
- Words will always be 5 letters long.
- If the letter matches: 🟩
- If the letter exists, but isn't in the right place: 🟨
- If the letter doesn't exist: ⬛
Example:
const solucion = "coche";
palabraSugerida("roble", solucion);
// ⬛🟩⬛⬛🟩
palabraSugerida("techo", solucion);
// ⬛🟨🟩🟩🟨
palabraSugerida("coche", solucion);
// 🟩🟩🟩🟩🟩
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.