Skip to content

Array methods #316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 40 commits into from
Jul 25, 2020
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
ea23430
Update article.md
nahuelcoder Jul 15, 2020
1a5fbd5
Update article.md
nahuelcoder Jul 16, 2020
77e3e5b
Updated article.md
nahuelcoder Jul 16, 2020
2568298
Updated article
nahuelcoder Jul 18, 2020
71a37c7
Updated article
nahuelcoder Jul 19, 2020
1c33c51
Updated article
nahuelcoder Jul 20, 2020
1836c4a
Updated traslation
nahuelcoder Jul 21, 2020
f49120e
Updated traslation
nahuelcoder Jul 22, 2020
11e85cf
Updated traslation
nahuelcoder Jul 22, 2020
e983eb0
Updated article
nahuelcoder Jul 22, 2020
6154afd
Updated traslation
nahuelcoder Jul 22, 2020
a866495
Merge pull request #2 from nahuelcoder/nahuelcoder-patch-1-Array-methods
nahuelcoder Jul 22, 2020
4610c80
Update task.md
nahuelcoder Jul 23, 2020
415c6d3
Update solution.js
nahuelcoder Jul 23, 2020
d4f3cf3
Update task.md
nahuelcoder Jul 23, 2020
9d676cd
Update 1-js/05-data-types/05-array-methods/11-array-unique/solution.md
nahuelcoder Jul 23, 2020
42a081e
Update 1-js/05-data-types/05-array-methods/12-reduce-object/task.md
nahuelcoder Jul 23, 2020
aeca5bf
Update 1-js/05-data-types/05-array-methods/12-reduce-object/task.md
nahuelcoder Jul 23, 2020
2c7509d
Update 1-js/05-data-types/05-array-methods/3-filter-range-in-place/ta…
nahuelcoder Jul 23, 2020
6534a30
Update 1-js/05-data-types/05-array-methods/6-calculator-extendable/so…
nahuelcoder Jul 23, 2020
a28bdfa
Update 1-js/05-data-types/05-array-methods/6-calculator-extendable/ta…
nahuelcoder Jul 23, 2020
88b688a
Update 1-js/05-data-types/05-array-methods/7-map-objects/solution.md
nahuelcoder Jul 23, 2020
77c3aa5
Update 1-js/05-data-types/05-array-methods/7-map-objects/solution.md
nahuelcoder Jul 23, 2020
55ffb74
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
bd70974
Update 1-js/05-data-types/05-array-methods/9-shuffle/solution.md
nahuelcoder Jul 23, 2020
ea5b99c
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
a294675
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
28b7b22
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
d047c86
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
0667f15
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
3efcd54
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
5b9c37c
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
2792030
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
bfa2c55
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
e62eee8
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
458f3f6
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
5f8f106
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
beba4b1
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
b8e291c
Update 1-js/05-data-types/05-array-methods/article.md
nahuelcoder Jul 23, 2020
b070c86
Update 1-js/05-data-types/05-array-methods/11-array-unique/solution.md
vplentinax Jul 24, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
function camelize(str) {
return str
.split('-') // splits 'my-long-word' into array ['my', 'long', 'word']
.split('-') // separa 'my-long-word' en el array ['my', 'long', 'word']
.map(
// capitalizes first letters of all array items except the first one
// converts ['my', 'long', 'word'] into ['my', 'Long', 'Word']
// convierte en mayúscula todas las primeras letras de los elemntos del array excepto por el primero
// convierte ['my', 'long', 'word'] en ['my', 'Long', 'Word']
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
)
.join(''); // joins ['my', 'Long', 'Word'] into 'myLongWord'
.join(''); // une ['my', 'Long', 'Word'] en 'myLongWord'
}
10 changes: 5 additions & 5 deletions 1-js/05-data-types/05-array-methods/1-camelcase/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ importance: 5

---

# Translate border-left-width to borderLeftWidth
# Transforma border-left-width en borderLeftWidth

Write the function `camelize(str)` that changes dash-separated words like "my-short-string" into camel-cased "myShortString".
Escribe la función `camelize(str)` que convierta palabras separadas por guión como "mi-cadena-corta" en palabras con mayúscula "miCadenaCorta".

That is: removes all dashes, each word after dash becomes uppercased.
Esto sería: remover todos los guiónes y que cada palabra después de un guión comience con mayúscula.

Examples:
Ejemplos:

```js
camelize("background-color") == 'backgroundColor';
camelize("list-style-image") == 'listStyleImage';
camelize("-webkit-transition") == 'WebkitTransition';
```

P.S. Hint: use `split` to split the string into an array, transform it and `join` back.
P.D. Pista: usa `split` para dividir el string en un array, transformalo y vuelve a unirlo (`join`).
8 changes: 4 additions & 4 deletions 1-js/05-data-types/05-array-methods/10-average-age/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 4

---

# Get average age
# Obtener edad promedio

Write the function `getAverageAge(users)` that gets an array of objects with property `age` and returns the average age.
Escribe la función `getAverageAge(users)` que obtenga un array de objetos con la propiedad `age` y devuelva el promedio de `age`.

The formula for the average is `(age1 + age2 + ... + ageN) / N`.
La fórmula de promedio es `(age1 + age2 + ... + ageN) / N`.

For instance:
Por ejemplo:

```js no-beautify
let john = { name: "John", age: 25 };
Expand Down
21 changes: 11 additions & 10 deletions 1-js/05-data-types/05-array-methods/11-array-unique/solution.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Let's walk the array items:
- For each item we'll check if the resulting array already has that item.
Recorramos los elementos dentro del array:
- Para cada elemento vamos a comprobar si el array resultante ya tiene ese elemento.
- If it is so, then ignore, otherwise add to results.
- Si ya lo tiene ignora y continúa, sino, agrega el resultado.

```js run demo
function unique(arr) {
Expand All @@ -22,18 +23,18 @@ let strings = ["Hare", "Krishna", "Hare", "Krishna",
alert( unique(strings) ); // Hare, Krishna, :-O
```

The code works, but there's a potential performance problem in it.
El código funciona pero tiene un problema potencial de desempeño.

The method `result.includes(str)` internally walks the array `result` and compares each element against `str` to find the match.
El método `result.includes(str)` internamente recorre el array `result` y compara cada elemento con `str` para encontrar una coincidencia.

So if there are `100` elements in `result` and no one matches `str`, then it will walk the whole `result` and do exactly `100` comparisons. And if `result` is large, like `10000`, then there would be `10000` comparisons.
Por lo tanto, si hay `100` elementos en `result` y ninguno coincide con `str`, entonces habrá recorrido todo el array `result` y ejecutado `100` comparaciones. Y si `result` ies grande, como `10000`, entonces habrá `10000` comparaciones.

That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds.
Esto no es un problema en sí mismo, porque los motores JavaScript son muy rápidos, por lo que recorrer `10000` elementos de un array solo le tomaría microsegundos.

But we do such test for each element of `arr`, in the `for` loop.
Pero ejecutamos dicha comprobación para cada elemento de `arr` en el loop `for`.

So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot.
Entonces si `arr.length` es `10000` vamos a tener algo como `10000*10000` = 100 millones de comparaciones. Esto es realmente mucho.

So the solution is only good for small arrays.
Por lo que la solución solo es buena para arrays pequeños.

Further in the chapter <info:map-set> we'll see how to optimize it.
Más adelante en el capítulo <info:map-set> vamos a ver como optimizarlo.
10 changes: 5 additions & 5 deletions 1-js/05-data-types/05-array-methods/11-array-unique/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 4

---

# Filter unique array members
# Filtrar elementos únicos de un array

Let `arr` be an array.
Partiendo del array `arr`.

Create a function `unique(arr)` that should return an array with unique items of `arr`.
Crea una función `unique(arr)` que devuelva un array con los elementos que se encuentran una sola vez dentro de `arr`.

For instance:
Por ejemplo:

```js
function unique(arr) {
/* your code */
/* tu código */
}

let strings = ["Hare", "Krishna", "Hare", "Krishna",
Expand Down
16 changes: 8 additions & 8 deletions 1-js/05-data-types/05-array-methods/12-reduce-object/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 4

---

# Create keyed object from array
# Crea un objeto con claves (key / property) a partir de un array

Let's say we received an array of users in the form `{id:..., name:..., age... }`.
Supongamos que recibimos un array de usuaris con la forma `{id:..., name:..., age... }`.

Create a function `groupById(arr)` that creates an object from it, with `id` as the key, and array items as values.
Crea una función `groupById(arr)` que cree un objeto, con `id` como clave (key) y los elementos del array como valores.

For example:
Por ejemplo:

```js
let users = [
Expand All @@ -20,7 +20,7 @@ let users = [
let usersById = groupById(users);

/*
// after the call we should have:
// después de llamar a la función deberíamos tener:

usersById = {
john: {id: 'john', name: "John Smith", age: 20},
Expand All @@ -30,8 +30,8 @@ usersById = {
*/
```

Such function is really handy when working with server data.
Dicha función es realmente útil cuando trabajamos con información del servidor.

In this task we assume that `id` is unique. There may be no two array items with the same `id`.
Para esta actividad asumimos que cada `id` es único. No existen dos elementos del array con el mismo `id`.

Please use array `.reduce` method in the solution.
Usa el método `array.reduce` en la solución.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

function filterRange(arr, a, b) {
// added brackets around the expression for better readability
// agregamos paréntesis en torno a la expresión para mayor legibilidad
return arr.filter(item => (a <= item && item <= b));
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
```js run demo
function filterRange(arr, a, b) {
// added brackets around the expression for better readability
// agregamos paréntesis en torno a la expresión para mayor legibilidad
return arr.filter(item => (a <= item && item <= b));
}

let arr = [5, 3, 8, 1];

let filtered = filterRange(arr, 1, 4);

alert( filtered ); // 3,1 (matching values)
alert( filtered ); // 3,1 (valores dentro del rango)

alert( arr ); // 5,3,8,1 (not modified)
alert( arr ); // 5,3,8,1 (array original no modificado)
```
12 changes: 6 additions & 6 deletions 1-js/05-data-types/05-array-methods/2-filter-range/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@ importance: 4

---

# Filter range
# Filtrar un rango

Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements between `a` and `b` in it and returns an array of them.
Escribe una función `filterRange(arr, a, b)` que obtenga un array `arr`, busque los elementos entre `a` y `b` y devuelva un array con los resultados.

The function should not modify the array. It should return the new array.
La función no debe modificar el array. Debe devolver un nuevo array.

For instance:
Por ejemplo:

```js
let arr = [5, 3, 8, 1];

let filtered = filterRange(arr, 1, 4);

alert( filtered ); // 3,1 (matching values)
alert( filtered ); // 3,1 (valores dentro del rango)

alert( arr ); // 5,3,8,1 (not modified)
alert( arr ); // 5,3,8,1 (array original no modificado)
```

Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) {
for (let i = 0; i < arr.length; i++) {
let val = arr[i];

// remove if outside of the interval
// remueve aquellos elementos que se encuentran fuera del intervalo
if (val < a || val > b) {
arr.splice(i, 1);
i--;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) {
for (let i = 0; i < arr.length; i++) {
let val = arr[i];

// remove if outside of the interval
// remueve aquellos elementos que se encuentran fuera del intervalo
if (val < a || val > b) {
arr.splice(i, 1);
i--;
Expand All @@ -15,7 +15,7 @@ function filterRangeInPlace(arr, a, b) {

let arr = [5, 3, 8, 1];

filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4
filterRangeInPlace(arr, 1, 4); // remueve los números excepto aquellos entre 1 y 4

alert( arr ); // [3, 1]
```
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 4

---

# Filter range "in place"
# Filtrar rango "en el lugar"

Write a function `filterRangeInPlace(arr, a, b)` that gets an array `arr` and removes from it all values except those that are between `a` and `b`. The test is: `a ≤ arr[i] ≤ b`.
Escrbe una función `filterRangeInPlace(arr, a, b)` que obtenga un array `arr` y remueva del mismo todos los valores excepto aquellos que se encuentran entre `a` y `b`. El test es: `a ≤ arr[i] ≤ b`.

The function should only modify the array. It should not return anything.
La función solo debe modificar el array. No debe devolver nada.

For instance:
Por ejemplo:
```js
let arr = [5, 3, 8, 1];

filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4
filterRangeInPlace(arr, 1, 4); // remueve los números excepto aquellos entre 1 y 4

alert( arr ); // [3, 1]
```
4 changes: 2 additions & 2 deletions 1-js/05-data-types/05-array-methods/4-sort-back/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ importance: 4

---

# Sort in decreasing order
# Ordenar en orden decreciente

```js
let arr = [5, 2, 1, -10, 8];

// ... your code to sort it in decreasing order
// ... tu código para ordenar en orden decreciente

alert( arr ); // 8, 5, 2, 1, -10
```
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
We can use `slice()` to make a copy and run the sort on it:
Podemos usar `slice()` para crear una copia y realizar el ordenamiento en ella:

```js run
function copySorted(arr) {
Expand Down
8 changes: 4 additions & 4 deletions 1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 5

---

# Copy and sort array
# Copia y ordena un array

We have an array of strings `arr`. We'd like to have a sorted copy of it, but keep `arr` unmodified.
Supongamos que tenemos un array `arr`. Nos gustaría tener una copia ordenada del mismo, pero mantener `arr` sin modificar.

Create a function `copySorted(arr)` that returns such a copy.
Crea una función `copySorted(arr)` que devuelva esa copia.

```js
let arr = ["HTML", "JavaScript", "CSS"];

let sorted = copySorted(arr);

alert( sorted ); // CSS, HTML, JavaScript
alert( arr ); // HTML, JavaScript, CSS (no changes)
alert( arr ); // HTML, JavaScript, CSS (sin cambios)
```
8 changes: 4 additions & 4 deletions 1-js/05-data-types/05-array-methods/6-array-get-names/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Map to names
# Mapa a nombres

You have an array of `user` objects, each one has `user.name`. Write the code that converts it into an array of names.
Tienes un array de objetos `user`, cada uno tiene `user.name`. Escribe el código que lo convierta en un array de nombres.

For instance:
Por ejemplo:

```js no-beautify
let john = { name: "John", age: 25 };
Expand All @@ -15,7 +15,7 @@ let mary = { name: "Mary", age: 28 };

let users = [ john, pete, mary ];

let names = /* ... your code */
let names = /* ... tu código */

alert( names ); // John, Pete, Mary
```
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@

- Please note how methods are stored. They are simply added to `this.methods` property.
- All tests and numeric conversions are done in the `calculate` method. In future it may be extended to support more complex expressions.
- Por favor ten en cuenta como los métodos son almacenados. Simplemente son agregados a la propiedad `this.methods`.
- Todos los test y conversiones son hechas con el método `calculate`. En el futuro puede ser extendido para soportar expresiones más complejas.
20 changes: 10 additions & 10 deletions 1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@ importance: 5

---

# Create an extendable calculator
# Crea una calculadora extensible

Create a constructor function `Calculator` that creates "extendable" calculator objects.
Crea una función `Calculator` que cree objetos calculadores "extensibles".

The task consists of two parts.
La actividad consiste de dos partes.

1. First, implement the method `calculate(str)` that takes a string like `"1 + 2"` in the format "NUMBER operator NUMBER" (space-delimited) and returns the result. Should understand plus `+` and minus `-`.
1. Primero, implementar el método `calculate(str)` que toma un string como `"1 + 2"` en el formato "NUMERO operador NUMERO" (delimitado por espacios) y devuelve el resultado. Debe entender más `+` y menos `-`.

Usage example:
Ejemplo de uso:

```js
let calc = new Calculator;

alert( calc.calculate("3 + 7") ); // 10
```
2. Then add the method `addMethod(name, func)` that teaches the calculator a new operation. It takes the operator `name` and the two-argument function `func(a,b)` that implements it.
2. Luego agrega el método `addMethod(name, func)` que enseñe a la calculadora una nueva operación. Toma el operador `name` y la función con dos argumentos `func(a,b)` que lo implementa.

For instance, let's add the multiplication `*`, division `/` and power `**`:
Por ejemplo, vamos a agregar la multiplicación `*`, division `/` y potencia `**`:

```js
let powerCalc = new Calculator;
Expand All @@ -31,6 +31,6 @@ The task consists of two parts.
alert( result ); // 8
```

- No parentheses or complex expressions in this task.
- The numbers and the operator are delimited with exactly one space.
- There may be error handling if you'd like to add it.
- Sin paréntesis ni expresiones complejas.
- Los números y el operador deben estar delimitados por exactamente un espacio.
- Puede haber manejo de errores si te gustaría agregarlo.
Loading