Skip to content

Array methods #109

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

Open
wants to merge 34 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
9f60b54
Topic about splice translated
adriavieira314 Feb 19, 2020
b545120
Minor changes on spelling
adriavieira314 Feb 19, 2020
3682d91
Slice method translated
adriavieira314 Feb 19, 2020
a515f5e
Minor changes in spelling
adriavieira314 Feb 19, 2020
d5e89d4
Minor changes in spelling
adriavieira314 Feb 19, 2020
0fbf0ab
Method concat translated
adriavieira314 Feb 19, 2020
001de77
ForEach method translated
adriavieira314 Feb 19, 2020
b754cce
Searching in Arrays translated
adriavieira314 Feb 19, 2020
01f5aeb
Filter, map and sort methods translated
Feb 20, 2020
7313e2a
Filter, map, sort, reverse, split and join methods translated
Feb 21, 2020
0de0510
Reduce method translated
Feb 21, 2020
709683d
Minor changes
Feb 21, 2020
0769724
Minor changes
Feb 21, 2020
4e22c2e
Array.isArray translated
Feb 22, 2020
9184f6c
Minor spelling changes
Feb 22, 2020
588b6e9
Summary translated
Feb 22, 2020
ce7ce92
Minor spelling changes
Feb 22, 2020
8a4a64c
Links changed to articles in portuguese
Feb 23, 2020
56545f4
Minor spelling changes
Feb 23, 2020
bba9814
solution.js translated
Feb 23, 2020
4e5f6b6
task camelcase translated
Feb 23, 2020
3c92031
Task filter range translated
Feb 23, 2020
c938a34
Task filter-range-in-place translated
Feb 23, 2020
0d4eebb
Task sort translated
Feb 23, 2020
2283adc
Task copy-and-sort translated
Feb 23, 2020
1570319
Task array-get-names translated
Feb 23, 2020
7cf4aa1
Task calculator translated
Feb 23, 2020
49cc586
Map objects task translated
Feb 23, 2020
10014f4
sort-objects task translated
Feb 23, 2020
dfaaada
minor spelling changes
Feb 23, 2020
b464660
shuffle task translated
Feb 23, 2020
04c309e
average-age task translated
Feb 23, 2020
be3a6e4
array-unique task translated
Feb 23, 2020
e654190
Titles from tasks translated
Feb 23, 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' em um array ['my', 'long', 'word']
.map(
// capitalizes first letters of all array items except the first one
// converts ['my', 'long', 'word'] into ['my', 'Long', 'Word']
// deixa as primeiras letras de todos os itens do array em maiúsculo exceto o primeiro item
// converte ['my', 'long', 'word'] em ['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'] formando '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
# Mude border-left-width para borderLeftWidth

Write the function `camelize(str)` that changes dash-separated words like "my-short-string" into camel-cased "myShortString".
Escreva uma função `camelize(str)` que mude as palavras separadas por traços como "my-short-string" para palavras em camelCase "myShortString".

That is: removes all dashes, each word after dash becomes uppercased.
Ou seja: remova todos os traços, cada palavra depois do traço precisa estar em maiúsculo.

Examples:
Exemplos:

```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.S. Dica: use `split` para separar a string em um array, transforme-os e os junte de volta usando `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
# Pegar a média de idade

Write the function `getAverageAge(users)` that gets an array of objects with property `age` and gets the average.
Escreva a função `getAverageAge(users)` que recebe um array de objetos com a propriedade `age` e pega a média entre eles.

The formula for the average is `(age1 + age2 + ... + ageN) / N`.
A fórmula da média é `(age1 + age2 + ... + ageN) / N`.

For instance:
Por exemplo:

```js no-beautify
let john = { name: "John", age: 25 };
Expand Down
22 changes: 11 additions & 11 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,6 @@
Let's walk the array items:
- For each item we'll check if the resulting array already has that item.
- If it is so, then ignore, otherwise add to results.
Vamos percorrer os itens do array:
- Para cada item, vamos checar se o array `result` já possui esse item.
- Se sim, então será ignorado, do contrário será adicionado a `result`.

```js run demo
function unique(arr) {
Expand All @@ -22,18 +22,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.
O código funciona, porém existe um potencial problema de performance aqui.

The method `result.includes(str)` internally walks the array `result` and compares each element against `str` to find the match.
O método `result.includes(str)` internamente percorre o array `result` e compara cada elemento com `str` para achar um que combine.

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.
Então se tiver `100` elementos em `result` e nenhum combine com `str`, então ele vai percorrer `result` inteiro e fazer exatamente `100` comparações. E se `result` for muito maior, como `10000`, então terá `10000` comparações.

That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds.
Isso não é um problema tão preocupante porque as engines do JavaScript são muito rápidas, então percorrer um array de `10000` itens dura questões de microsegundos.

But we do such test for each element of `arr`, in the `for` loop.
Porém, nós estamos fazendo estes teste para cada elemento em `arr` no laço de repetição `for`.

So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot.
Então se `arr.length` for `10000` vamos ter algo como: `10000*10000` = 100 milhões de comparações. Isso é muito.

So the solution is only good for small arrays.
Então, essa solução é somente boa para arrays pequenas.

Further in the chapter <info:map-set-weakmap-weakset> we'll see how to optimize it.
Mais adiante no capítulo <info:map-set-weakmap-weakset> vamos ver como otimizar isso.
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
# Filtre membros únicos de um array

Let `arr` be an array.
Deixe `arr` ser um array.

Create a function `unique(arr)` that should return an array with unique items of `arr`.
Crie a função `unique(arr)` que recebe um array `string` e retorna outro array `arr` com itens únicos/que mais se repetem do array recebido.

For instance:
Por exemplo:

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

let strings = ["Hare", "Krishna", "Hare", "Krishna",
Expand Down
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
// colchetes adicionado ao redor da expressão para melhor entendimento
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
// colchetes adicionado ao redor da expressão para melhor entendimento
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 que coincidem com o que foi pedido)

alert( arr ); // 5,3,8,1 (not modified)
alert( arr ); // 5,3,8,1 (array não foi modificada)
```
10 changes: 5 additions & 5 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 @@ -4,19 +4,19 @@ importance: 4

# Filter range

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.
Escreva uma função `filterRange(arr, a, b)` que pegue um array `arr`, procure por elementos entre `a` e `b` e retorne um array novo com os elementos encontrados.

The function should not modify the array. It should return the new array.
A função não deve modificar o array. Deve retornar um novo array.

For instance:
Exemplo:

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

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

alert( filtered ); // 3,1 (matching values)
alert( filtered ); // 3,1 (valores que coincidem com o que foi pedido)

alert( arr ); // 5,3,8,1 (not modified)
alert( arr ); // 5,3,8,1 (array não foi modificada)
```

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
//remove se estiver fora do 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
//remove se estiver fora do 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); // remove os números exceto números de 1 á 4

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

# Filter range "in place"

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`.
Escreva uma função `filterRangeInPlace(arr, a, b)` que pegue um array `arr` e remova dele todos os valores exceto aqueles que estão entre `a` e `b`. A condição é: `a ≤ arr[i] ≤ b`.

The function should only modify the array. It should not return anything.
A função deve modificar a array. Não deve retornar um valor.

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

filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4
filterRangeInPlace(arr, 1, 4); // remove os números exceto números de 1 á 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 the reverse order
# Ordene (sort) na ordem decrescente

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

// ... your code to sort it in the reverse order
// ... seu código para ordenar na ordem decrescente

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 fazer a cópia e executar o método `sort()` logo depois:

```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
# Copie e ordene o array

We have an array of strings `arr`. We'd like to have a sorted copy of it, but keep `arr` unmodified.
Temos um array de strings `arr`. Gostaríamos de ter uma copia ordenada desse array, porém mantenha `arr` do mesmo jeito, sem modificações.

Create a function `copySorted(arr)` that returns such a copy.
Crie uma função `copySorted(arr)` que retorna a 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 (arr sem alterções)
```
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
# Map para nomes

You have an array of `user` objects, each one has `user.name`. Write the code that converts it into an array of names.
Você tem um array de objetos `user`, cada um possui `user.name`. Escreva um código que converta o array para um array de nomes.

For instance:
Exemplo:

```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 = /* ... seu 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 the internal object.
- All tests and numeric conversions are done in the `calculate` method. In future it may be extended to support more complex expressions.
- Por favor, note como os métodos são armazenados. Eles são simplesmente adicionados no objeto interno.
- Todos os testes e conversões numéricas são feitas no método `calculate`. No futuro, pode ser extendida para suportar mais expressões complexas.
27 changes: 15 additions & 12 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,35 +2,38 @@ importance: 5

---

# Create an extendable calculator
# Crie uma calculadora extensível

Create a constructor function `Calculator` that creates "extendable" calculator objects.
Construa uma função construtora `Calculator` que crie objetos de calculadora "extensível".

The task consists of two parts.
A atividade consiste de duas 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. Primeiro, implemente o método `calculate(str)` que pegue uma string como `"1 + 2"` e a deixe no formato "NÚMERO operador NÚMERO" (delimitada por espaços) e retorne o resultado. Deve entender os operadores mais `+` e menos `-`.

Usage example:
Exemplo:

```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. Então, adicione o método `addMethod(name, func)` que ensina a calculadora uma nova operação. O método pega o operador `name` e a função que recebe dois argumentos `func(a,b)` para implementar a nova operação.

For instance, let's add the multiplication `*`, division `/` and power `**`:
Por exemplo, vamos adicionar multiplicação `*`, divisão `/` e potenciação `**`:

```js
let multCalc = new Calculator;
let divCalc = new Calculator;
let powerCalc = new Calculator;
powerCalc.addMethod("*", (a, b) => a * b);
powerCalc.addMethod("/", (a, b) => a / b);

multCalc.addMethod("*", (a, b) => a * b);
divCalc.addMethod("/", (a, b) => a / b);
powerCalc.addMethod("**", (a, b) => a ** b);

let result = powerCalc.calculate("2 ** 3");
alert( result ); // 8
```

- No brackets 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.
- Sem colchetes ou expressões complexas neste exercício.
- Os números e o operador são separados por, exatamente, um espaço.
- Pode haver mensagem de erro se você desejar adicionar.
10 changes: 5 additions & 5 deletions 1-js/05-data-types/05-array-methods/7-map-objects/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,19 @@ alert( usersMapped[0].id ); // 1
alert( usersMapped[0].fullName ); // John Smith
```

Please note that in for the arrow functions we need to use additional brackets.
Por favor, note que para usar arrow functions, precisamos usar colchetes adicionais.

We can't write like this:
Não podemos escrevê-lo dessa forma:
```js
let usersMapped = users.map(user => *!*{*/!*
fullName: `${user.name} ${user.surname}`,
id: user.id
});
```

As we remember, there are two arrow functions: without body `value => expr` and with body `value => {...}`.
Como sabemos, existem dois tipos de arrow functions: sem corpo `value => expr` e com corpo `value => {...}`.

Here JavaScript would treat `{` as the start of function body, not the start of the object. The workaround is to wrap them in the "normal" brackets:
JavaScript irá tratar `{` como o começo do corpo de uma função, não o começo do objeto. A *gambiarra* é os colocar em volta de colchetes "normais", ou seja, primeiro os parênteses e depois os colchetes `({ ... })`:

```js
let usersMapped = users.map(user => *!*({*/!*
Expand All @@ -46,6 +46,6 @@ let usersMapped = users.map(user => *!*({*/!*
}));
```

Now fine.
Dessa forma, nosso código está correto.


Loading