diff --git a/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js b/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js index 490f570ad..00bcc78e9 100644 --- a/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js @@ -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' } diff --git a/1-js/05-data-types/05-array-methods/1-camelcase/task.md b/1-js/05-data-types/05-array-methods/1-camelcase/task.md index ef5944636..fdd3e5161 100644 --- a/1-js/05-data-types/05-array-methods/1-camelcase/task.md +++ b/1-js/05-data-types/05-array-methods/1-camelcase/task.md @@ -2,13 +2,13 @@ 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'; @@ -16,4 +16,4 @@ 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`. diff --git a/1-js/05-data-types/05-array-methods/10-average-age/task.md b/1-js/05-data-types/05-array-methods/10-average-age/task.md index bf5f85df3..2e3e7525e 100644 --- a/1-js/05-data-types/05-array-methods/10-average-age/task.md +++ b/1-js/05-data-types/05-array-methods/10-average-age/task.md @@ -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 returns the average age. +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 }; diff --git a/1-js/05-data-types/05-array-methods/11-array-unique/solution.md b/1-js/05-data-types/05-array-methods/11-array-unique/solution.md index b9d627a0a..0e40466de 100644 --- a/1-js/05-data-types/05-array-methods/11-array-unique/solution.md +++ b/1-js/05-data-types/05-array-methods/11-array-unique/solution.md @@ -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) { @@ -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 we'll see how to optimize it. +Mais adiante no capítulo vamos ver como otimizar isso. diff --git a/1-js/05-data-types/05-array-methods/11-array-unique/task.md b/1-js/05-data-types/05-array-methods/11-array-unique/task.md index 5b56d3621..56a6e4579 100644 --- a/1-js/05-data-types/05-array-methods/11-array-unique/task.md +++ b/1-js/05-data-types/05-array-methods/11-array-unique/task.md @@ -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 deve retornar um array com itens únicos de `arr`. -For instance: +Por exemplo: ```js function unique(arr) { - /* your code */ + /* seu código */ } let strings = ["Hare", "Krishna", "Hare", "Krishna", diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js b/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js index 0bdfbae5a..2a82ac377 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js @@ -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)); } \ No newline at end of file diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/solution.md b/1-js/05-data-types/05-array-methods/2-filter-range/solution.md index 73993a07a..39c83cfc7 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/solution.md +++ b/1-js/05-data-types/05-array-methods/2-filter-range/solution.md @@ -1,6 +1,6 @@ ```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)); } @@ -8,7 +8,7 @@ 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) ``` diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/task.md b/1-js/05-data-types/05-array-methods/2-filter-range/task.md index 46e47c93d..b4068f0aa 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/task.md +++ b/1-js/05-data-types/05-array-methods/2-filter-range/task.md @@ -4,19 +4,19 @@ importance: 4 # Filter range -Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements with values higher or equal to `a` and lower or equal to `b` and return a result as an array. +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) ``` diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js index 488db3755..f9af1a4f3 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js @@ -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--; diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md index 36e3130ff..9301242ea 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md @@ -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--; @@ -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] ``` diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md index 7066a51ab..86008af7f 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md @@ -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] ``` diff --git a/1-js/05-data-types/05-array-methods/4-sort-back/task.md b/1-js/05-data-types/05-array-methods/4-sort-back/task.md index 0e3eeab76..d6234efa8 100644 --- a/1-js/05-data-types/05-array-methods/4-sort-back/task.md +++ b/1-js/05-data-types/05-array-methods/4-sort-back/task.md @@ -2,12 +2,12 @@ importance: 4 --- -# Sort in decreasing order +# Ordene (sort) na ordem decrescente ```js let arr = [5, 2, 1, -10, 8]; -// ... your code to sort it in decreasing order +// ... seu código para ordenar na ordem decrescente alert( arr ); // 8, 5, 2, 1, -10 ``` diff --git a/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md b/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md index 8537b129e..2f05fe24e 100644 --- a/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md +++ b/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md @@ -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) { diff --git a/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md b/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md index c1395b4ad..b12e76704 100644 --- a/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md +++ b/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md @@ -2,11 +2,11 @@ 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"]; @@ -14,5 +14,5 @@ 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) ``` diff --git a/1-js/05-data-types/05-array-methods/6-array-get-names/task.md b/1-js/05-data-types/05-array-methods/6-array-get-names/task.md index 74c8a9d74..a5c9c0b51 100644 --- a/1-js/05-data-types/05-array-methods/6-array-get-names/task.md +++ b/1-js/05-data-types/05-array-methods/6-array-get-names/task.md @@ -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 }; @@ -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 ``` diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md b/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md index ebe0714cf..b8c02d903 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md @@ -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, 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. diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md b/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md index e0d302f4c..c7e550512 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md @@ -2,24 +2,24 @@ 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 powerCalc = new Calculator; @@ -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. +- 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. diff --git a/1-js/05-data-types/05-array-methods/7-map-objects/solution.md b/1-js/05-data-types/05-array-methods/7-map-objects/solution.md index 2d8d4fb0e..a29000f59 100644 --- a/1-js/05-data-types/05-array-methods/7-map-objects/solution.md +++ b/1-js/05-data-types/05-array-methods/7-map-objects/solution.md @@ -25,9 +25,9 @@ alert( usersMapped[0].id ); // 1 alert( usersMapped[0].fullName ); // John Smith ``` -Please note that in 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}`, @@ -35,9 +35,9 @@ let usersMapped = users.map(user => *!*{*/!* }); ``` -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": ```js let usersMapped = users.map(user => *!*({*/!* @@ -46,6 +46,6 @@ let usersMapped = users.map(user => *!*({*/!* })); ``` -Now fine. +Dessa forma, nosso código está correto. diff --git a/1-js/05-data-types/05-array-methods/7-map-objects/task.md b/1-js/05-data-types/05-array-methods/7-map-objects/task.md index b11d12155..d69026790 100644 --- a/1-js/05-data-types/05-array-methods/7-map-objects/task.md +++ b/1-js/05-data-types/05-array-methods/7-map-objects/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Map to objects +# Map para objetos -You have an array of `user` objects, each one has `name`, `surname` and `id`. +Você tem um array de objetos `user`, cada um possui `name`, `surname` e `id`. -Write the code to create another array from it, of objects with `id` and `fullName`, where `fullName` is generated from `name` and `surname`. +Escreva um código para criar um novo array a partir de `user`, também será um array de objetos com as propriedades `id` e `fullName`, onde `fullName` é gerado a partir da junção de `name` e `surname`. -For instance: +Exemplo: ```js no-beautify let john = { name: "John", surname: "Smith", id: 1 }; @@ -18,7 +18,7 @@ let mary = { name: "Mary", surname: "Key", id: 3 }; let users = [ john, pete, mary ]; *!* -let usersMapped = /* ... your code ... */ +let usersMapped = /* ... seu código ... */ */!* /* @@ -33,4 +33,4 @@ alert( usersMapped[0].id ) // 1 alert( usersMapped[0].fullName ) // John Smith ``` -So, actually you need to map one array of objects to another. Try using `=>` here. There's a small catch. \ No newline at end of file +Então, na realidade, você precisa copiar um array de objetos para o outro. Tente usar `=>` aqui. Há uma pegadinha neste exercício. \ No newline at end of file diff --git a/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md b/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md index cfaf9761a..2f32b4617 100644 --- a/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md +++ b/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md @@ -11,7 +11,7 @@ let arr = [ pete, john, mary ]; sortByAge(arr); -// now sorted is: [john, mary, pete] +// agora a ordenação: [john, mary, pete] alert(arr[0].name); // John alert(arr[1].name); // Mary alert(arr[2].name); // Pete diff --git a/1-js/05-data-types/05-array-methods/8-sort-objects/task.md b/1-js/05-data-types/05-array-methods/8-sort-objects/task.md index 9a215c9f4..35559fffd 100644 --- a/1-js/05-data-types/05-array-methods/8-sort-objects/task.md +++ b/1-js/05-data-types/05-array-methods/8-sort-objects/task.md @@ -2,11 +2,11 @@ importance: 5 --- -# Sort users by age +# Ordene (sort) users por age -Write the function `sortByAge(users)` that gets an array of objects with the `age` property and sorts them by `age`. +Escreva a função `sortByAge(users)` que recebe um array de objetos com a propriedade `age` e o ordene por `age`. -For instance: +Por exemplo: ```js no-beautify let john = { name: "John", age: 25 }; @@ -17,7 +17,7 @@ let arr = [ pete, john, mary ]; sortByAge(arr); -// now: [john, mary, pete] +// agora: [john, mary, pete] alert(arr[0].name); // John alert(arr[1].name); // Mary alert(arr[2].name); // Pete diff --git a/1-js/05-data-types/05-array-methods/9-shuffle/solution.md b/1-js/05-data-types/05-array-methods/9-shuffle/solution.md index 6674c444f..c86bb4345 100644 --- a/1-js/05-data-types/05-array-methods/9-shuffle/solution.md +++ b/1-js/05-data-types/05-array-methods/9-shuffle/solution.md @@ -1,4 +1,4 @@ -The simple solution could be: +A solução simples pode ser: ```js run *!* @@ -12,18 +12,18 @@ shuffle(arr); alert(arr); ``` -That somewhat works, because `Math.random() - 0.5` is a random number that may be positive or negative, so the sorting function reorders elements randomly. +O código acima funciona porque `Math.random() - 0.5` é um número aleatório que pode ser positivo ou negativo, então a função de ordenação reordena os elementos aleatoriamente. -But because the sorting function is not meant to be used this way, not all permutations have the same probability. +Mas porque a função de ordenação não deve ser usada dessa maneira, nem todas as permutações têm a mesma probabilidade. -For instance, consider the code below. It runs `shuffle` 1000000 times and counts appearances of all possible results: +Por exemplo, considere o código abaixo. Ele executa `shuffle` 1000000 vezes e conta quantas foram as aparições de todos os resultados possíveis: ```js run function shuffle(array) { array.sort(() => Math.random() - 0.5); } -// counts of appearances for all possible permutations +// contagem de aparições de todos as permutações possíveis let count = { '123': 0, '132': 0, @@ -39,13 +39,13 @@ for (let i = 0; i < 1000000; i++) { count[array.join('')]++; } -// show counts of all possible permutations +// mostra a contagem de aparições de todos as permutações possíveis for (let key in count) { alert(`${key}: ${count[key]}`); } ``` -An example result (depends on JS engine): +Um exemplo do resultado (depende do motor JS): ```js 123: 250706 @@ -56,30 +56,30 @@ An example result (depends on JS engine): 321: 125223 ``` -We can see the bias clearly: `123` and `213` appear much more often than others. +Podemos ver claramente: `123` e `213` aparece muito mais vezes do que os outros. -The result of the code may vary between JavaScript engines, but we can already see that the approach is unreliable. +O resultado do código pode variar entre as engines do JavaScript, mas já podemos ver que essa proposta não é confiável. -Why it doesn't work? Generally speaking, `sort` is a "black box": we throw an array and a comparison function into it and expect the array to be sorted. But due to the utter randomness of the comparison the black box goes mad, and how exactly it goes mad depends on the concrete implementation that differs between engines. +Por que não? Falando no geral, `sort` é uma "caixa preta": entregamos um array e uma função de comparação para ele e esperamos que o array seja ordenado. Porém, devido á aleatoriariedade total da comparação a caixa preta "enlouquece", e como exatamente ele "enlouquece" depende da implementação concreta que diferencia entre engines. -There are other good ways to do the task. For instance, there's a great algorithm called [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). The idea is to walk the array in the reverse order and swap each element with a random one before it: +Há outras formas melhores para fazer essa atividade. Por exemplo, existe um ótimo algoritmo chamado [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). A idéia é percorrer o array na ordem inversa e trocar cada elemento por um aleatório antes dele: ```js function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { - let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i + let j = Math.floor(Math.random() * (i + 1)); // index aleatório de 0 á i - // swap elements array[i] and array[j] - // we use "destructuring assignment" syntax to achieve that - // you'll find more details about that syntax in later chapters - // same can be written as: + // troca os elementos do array[i] e do array[j] + // nós usamos a sintaxe "atribuição de desestruturação" para conseguir isso + // você vai encontrar mais detalhes sobre essa sintaxe em capítulos posteriores + // também pode ser escrito dessa forma: // let t = array[i]; array[i] = array[j]; array[j] = t [array[i], array[j]] = [array[j], array[i]]; } } ``` -Let's test it the same way: +Vamos testá-lo: ```js run function shuffle(array) { @@ -89,7 +89,7 @@ function shuffle(array) { } } -// counts of appearances for all possible permutations +// contagem de aparições de todos as permutações possíveis let count = { '123': 0, '132': 0, @@ -105,13 +105,13 @@ for (let i = 0; i < 1000000; i++) { count[array.join('')]++; } -// show counts of all possible permutations +// mostra a contagem de aparições de todos as permutações possíveis for (let key in count) { alert(`${key}: ${count[key]}`); } ``` -The example output: +O resultado do exemplo: ```js 123: 166693 @@ -122,6 +122,6 @@ The example output: 321: 166316 ``` -Looks good now: all permutations appear with the same probability. +Parece bom agora: todas as permutações aparecem com a mesma probabilidade. -Also, performance-wise the Fisher-Yates algorithm is much better, there's no "sorting" overhead. +Além disso, em termos de performance, o algoritmo Fisher-Yates é muito melhor, não há sobrecarga de ordenação. diff --git a/1-js/05-data-types/05-array-methods/9-shuffle/task.md b/1-js/05-data-types/05-array-methods/9-shuffle/task.md index 970c53417..baebef22e 100644 --- a/1-js/05-data-types/05-array-methods/9-shuffle/task.md +++ b/1-js/05-data-types/05-array-methods/9-shuffle/task.md @@ -2,11 +2,11 @@ importance: 3 --- -# Shuffle an array +# Embaralhe um array -Write the function `shuffle(array)` that shuffles (randomly reorders) elements of the array. +Escreva a função `shuffle(array)` que embaralha (reordena aleatoriamente) elementos do array. -Multiple runs of `shuffle` may lead to different orders of elements. For instance: +Múltiplas execuções de `shuffle` pode levar para diferentes ordenações dos elementos. Por exemplo: ```js let arr = [1, 2, 3]; @@ -22,4 +22,4 @@ shuffle(arr); // ... ``` -All element orders should have an equal probability. For instance, `[1,2,3]` can be reordered as `[1,2,3]` or `[1,3,2]` or `[3,1,2]` etc, with equal probability of each case. +Todas as ordenações dos elementos deve ter uma probabilidade igual. Por exemplo, `[1,2,3]` pode ser reordenado como `[1,2,3]` ou `[1,3,2]` ou `[3,1,2]` etc, com probabilidade iguais para cada caso. diff --git a/1-js/05-data-types/05-array-methods/article.md b/1-js/05-data-types/05-array-methods/article.md index abd05022f..084aec6e1 100644 --- a/1-js/05-data-types/05-array-methods/article.md +++ b/1-js/05-data-types/05-array-methods/article.md @@ -1,111 +1,111 @@ -# Array methods +# Métodos Arrays -Arrays provide a lot of methods. To make things easier, in this chapter, they are split into groups. +Arrays nos fornece vários métodos. Para deixar esse assunto mais fácil de entender, neste capítulo esses métodos estão divididos em grupos. -## Add/remove items +## Adicionar/Remover itens -We already know methods that add and remove items from the beginning or the end: +Nós já conhecemos os métodos que adicionam e removem itens do início ou fim de um array: -- `arr.push(...items)` -- adds items to the end, -- `arr.pop()` -- extracts an item from the end, -- `arr.shift()` -- extracts an item from the beginning, -- `arr.unshift(...items)` -- adds items to the beginning. +- `arr.push(...itens)` -- adiciona itens no final de um array, +- `arr.pop()` -- retira um item do final de um array, +- `arr.shift()` -- retira um item do começo de um array, +- `arr.unshift(...itens)` -- adiciona itens no começo de um array. -Here are a few others. +Abaixo apresentamos alguns outros métodos. ### splice -How to delete an element from the array? +Como deletar um elemento de um array? -The arrays are objects, so we can try to use `delete`: +Arrays são objetos, então podemos tentar usar `delete`: ```js run -let arr = ["I", "go", "home"]; +let arr = ["Eu", "vou", "casa"]; -delete arr[1]; // remove "go" +delete arr[1]; // remove "vou" -alert( arr[1] ); // undefined +alert( arr[1] ); // retornará undefined pois o elemento foi apagado -// now arr = ["I", , "home"]; +// atualizado arr = ["Eu", , "casa"]; alert( arr.length ); // 3 ``` -The element was removed, but the array still has 3 elements, we can see that `arr.length == 3`. +O elemento foi removido, mas o array ainda possui 3 elementos, nós podemos ver que `arr.length == 3`. -That's natural, because `delete obj.key` removes a value by the `key`. It's all it does. Fine for objects. But for arrays we usually want the rest of the elements to shift and occupy the freed place. We expect to have a shorter array now. +Isso é normal porque `delete obj.key` remove o valor pela `key`. É um bom uso para objetos, mas para arrays, nós, normalmente, queremos que o resto dos elementos se movam e ocupem o espaço liberado. Esperávamos um array com menos elementos. -So, special methods should be used. +Dessa forma, métodos especiais devem ser usados. -The [arr.splice](mdn:js/Array/splice) method is a Swiss army knife for arrays. It can do everything: insert, remove and replace elements. +O metodo [arr.splice(str)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) é um canivete suíço para arrays. Ele pode fazer qualquer coisa: adicionar, remover e inserir elementos. -The syntax is: +Sua sintaxe é: ```js arr.splice(start[, deleteCount, elem1, ..., elemN]) ``` -It modifies `arr` starting from the index `start`: removes `deleteCount` elements and then inserts `elem1, ..., elemN` at their place. Returns the array of removed elements. +Começa em uma posição `start`: remove uma certa `deleteCount` de elementos e então insere `elem1, ..., elemN` em seus lugares. Ele retorna um array com os elementos removidos. -This method is easy to grasp by examples. +Esse metódo é melhor de se entender com exemplos. -Let's start with the deletion: +Vamos começar com a remoção de elementos: ```js run -let arr = ["I", "study", "JavaScript"]; +let arr = ["Eu", "estudo", "JavaScript"]; *!* -arr.splice(1, 1); // from index 1 remove 1 element +arr.splice(1, 1); // a partir da posição 1 remova 1 elemento */!* -alert( arr ); // ["I", "JavaScript"] +alert( arr ); // ["Eu", "JavaScript"] ``` -Easy, right? Starting from the index `1` it removed `1` element. +Fácil, não é? Começando pela posição `1` o método removeu `1` elemento. -In the next example, we remove 3 elements and replace them with the other two: +No próximo exemplo vamos remover 3 elementos e substituí-los por outros dois elementos: ```js run -let arr = [*!*"I", "study", "JavaScript",*/!* "right", "now"]; +let arr = [*!*"Eu", "estudo", "JavaScript",*/!* "agora", "mesmo"]; -// remove 3 first elements and replace them with another -arr.splice(0, 3, "Let's", "dance"); +// remove os 3 primeiros elementos e os substitui por outros +arr.splice(0, 3, "Vamos", "dançar"); -alert( arr ) // now [*!*"Let's", "dance"*/!*, "right", "now"] +alert( arr ) // atualizado [*!*"Vamos", "dançar"*/!*, "agora", "mesmo"] ``` -Here we can see that `splice` returns the array of removed elements: +Abaixo podemos ver que `splice` retorna um array dos elementos removidos: ```js run -let arr = [*!*"I", "study",*/!* "JavaScript", "right", "now"]; +let arr = [*!*"Eu", "estudo",*/!* "JavaScript", "agora", "mesmo"]; -// remove 2 first elements +// remove os 2 primeiros elementos let removed = arr.splice(0, 2); -alert( removed ); // "I", "study" <-- array of removed elements +alert( removed ); // "Eu", "estudo" <-- array de elementos removidos ``` -The `splice` method is also able to insert the elements without any removals. For that, we need to set `deleteCount` to `0`: +O método `splice` também permite inserir elementos sem remover outros. Para isso, devemos colocar a `deleteCount` em `0`: ```js run -let arr = ["I", "study", "JavaScript"]; +let arr = ["Eu", "estudo", "JavaScript"]; -// from index 2 -// delete 0 -// then insert "complex" and "language" -arr.splice(2, 0, "complex", "language"); +// a partir da posição 2 +// delete 0 elementos +// então insira "linguagem" e "complexa" +arr.splice(2, 0, "linguagem", "complexa"); -alert( arr ); // "I", "study", "complex", "language", "JavaScript" +alert( arr ); // "Eu", "estudo", "linguagem", "complexa", "JavaScript" ``` -````smart header="Negative indexes allowed" -Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like here: +````smart header="Posição negativas são permitidas" +Neste e em outros métodos arrays, posições negativas são permitidas. Eles especificam a posição a partir do fim de um array, por exemplo: ```js run let arr = [1, 2, 5]; -// from index -1 (one step from the end) -// delete 0 elements, -// then insert 3 and 4 +// a partir da posição -1 (uma posição antes da última) +// delete 0 elementos, +// então insira 3 e 4 arr.splice(-1, 0, 3, 4); alert( arr ); // 1,2,3,4,5 @@ -114,19 +114,19 @@ alert( arr ); // 1,2,3,4,5 ### slice -The method [arr.slice](mdn:js/Array/slice) is much simpler than the similar-looking `arr.splice`. +O método [arr.slice](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) é mais simples do que seu similar anterior `arr.splice`. -The syntax is: +Sua sintaxe é: ```js arr.slice([start], [end]) ``` -It returns a new array copying to it all items from index `start` to `end` (not including `end`). Both `start` and `end` can be negative, in that case position from array end is assumed. +Ele retorna um novo array contendo todos os itens a partir da posição `start` até `end` (ele não inclui o valor da posição `end`). Ambos `start` e `end` podem ser negativos, nesse caso, a posição do final da array é assumida. -It's similar to a string method `str.slice`, but instead of substrings, it makes subarrays. +Funciona como `str.slice`, porém este cria subarrays em vez de substrings. -For instance: +Por exemplo: ```js run let arr = ["t", "e", "s", "t"]; @@ -140,108 +140,108 @@ We can also call it without arguments: `arr.slice()` creates a copy of `arr`. Th ### concat -The method [arr.concat](mdn:js/Array/concat) creates a new array that includes values from other arrays and additional items. +O método [arr.concat](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) Cria um novo array que inclui valores de outros arrays e itens adicionais. -The syntax is: +Sua sintaxe é: ```js arr.concat(arg1, arg2...) ``` -It accepts any number of arguments -- either arrays or values. +Este método aceita qualquer número de argumentos -- sendo arrays ou valores. -The result is a new array containing items from `arr`, then `arg1`, `arg2` etc. +O resultado vai ser um novo array contendo itens do `arr`, e também do `arg1`, `arg2` etc. -If an argument `argN` is an array, then all its elements are copied. Otherwise, the argument itself is copied. +Se o argumento `argN` for um array, todos os seus elementos serão copiados. Caso contrário, o próprio argumento será copiado. -For instance: +Veja o exemplo: ```js run let arr = [1, 2]; -// create an array from: arr and [3,4] -alert( arr.concat([3, 4]) ); // 1,2,3,4 +// cria um array a partir de: arr e [3,4] +alert( arr.concat([3, 4])); // 1,2,3,4 -// create an array from: arr and [3,4] and [5,6] -alert( arr.concat([3, 4], [5, 6]) ); // 1,2,3,4,5,6 +// cria um array a partir de: arr, [3,4] e [5,6] +alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6 -// create an array from: arr and [3,4], then add values 5 and 6 -alert( arr.concat([3, 4], 5, 6) ); // 1,2,3,4,5,6 +// cria um array a partir de: arr e [3,4], então adiciona os valores 5 e 6 +alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6 ``` -Normally, it only copies elements from arrays. Other objects, even if they look like arrays, are added as a whole: +Normalmente, ele somente copia elementos de um array. Outros objetos, mesmo que eles se pareçam com arrays, são adicionados como um todo: ```js run let arr = [1, 2]; let arrayLike = { - 0: "something", + 0: "algo", length: 1 }; -alert( arr.concat(arrayLike) ); // 1,2,[object Object] +alert( arr.concat(arrayLike) ); // 1,2,[objeto Objeto] ``` -...But if an array-like object has a special `Symbol.isConcatSpreadable` property, then it's treated as an array by `concat`: its elements are added instead: +...Mas se um array parecido com um objeto possui a propriedade `Symbol.isConcatSpreadable`, então é tratado como um array pelo `concat` seus elementos são somados: ```js run let arr = [1, 2]; let arrayLike = { - 0: "something", - 1: "else", + 0: "qualquer", + 1: "coisa", *!* [Symbol.isConcatSpreadable]: true, */!* length: 2 }; -alert( arr.concat(arrayLike) ); // 1,2,something,else +alert( arr.concat(arrayLike) ); // 1,2,qualquer,coisa ``` ## Iterate: forEach -The [arr.forEach](mdn:js/Array/forEach) method allows to run a function for every element of the array. +O método [arr.forEach](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) permite executar uma função para cada elemento de um array. -The syntax: +Sua sintaxe: ```js arr.forEach(function(item, index, array) { - // ... do something with an item + // ... faça algo com o item }); ``` -For instance, this shows each element of the array: +Observe o exemplo abaixo, o código mostra cada elemento de um array: ```js run -// for each element call alert +// para cada elemento chame o alert ["Bilbo", "Gandalf", "Nazgul"].forEach(alert); ``` -And this code is more elaborate about their positions in the target array: +Este código é mais elaborado e mostra a posição de cada elemento: ```js run ["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => { - alert(`${item} is at index ${index} in ${array}`); + alert(`${item} está na posição ${index} em ${array}`); }); ``` -The result of the function (if it returns any) is thrown away and ignored. +O resultado da função (se retornar algum) é descartado e ignorado. -## Searching in array +## Buscando valores em um array -Now let's cover methods that search in an array. +Estes são métodos para procurar algo em um array. -### indexOf/lastIndexOf and includes +### indexOf/lastIndexOf e includes -The methods [arr.indexOf](mdn:js/Array/indexOf) and [arr.includes](mdn:js/Array/includes) have the similar syntax and do essentially the same as their string counterparts, but operate on items instead of characters: +Os métodos [arr.indexOf](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) e [arr.includes](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/contains) possuem a mesma sintaxe e fazem, essencialmente, a mesma coisa que acontece com as strings, entretanto, eles operam nos itens de um array em vez de caracteres como feito nas strings: -- `arr.indexOf(item, from)` -- looks for `item` starting from index `from`, and returns the index where it was found, otherwise `-1`. -- `arr.includes(item, from)` -- looks for `item` starting from index `from`, returns `true` if found. +- `arr.indexOf(item, from)` -- procura por `item` começando pela posição `from`, e retorna o index/posição onde o elemento foi encontrado, caso o elemento não seja encontrado, o método retornará `-1`. +- `arr.includes(item, from)` -- procura por `item` começando da posição `from`, retorna `true` se achado. -Usually these methods are used with only one argument: the `item` to search. By default, the search is from the beginning. +Normalmente, esses métodos são usados com apenas um argumento: o `item` a ser pesquisado. Por padrão, a pesquisa é feita desde o início. -For instance: +Veja o exemplo: ```js run let arr = [1, 0, false]; @@ -253,53 +253,53 @@ alert( arr.indexOf(null) ); // -1 alert( arr.includes(1) ); // true ``` -Please note that `indexOf` uses the strict equality `===` for comparison. So, if we look for `false`, it finds exactly `false` and not the zero. +Observe que `indexOf` usa a igualdade estrita `===` para comparação. Portanto, se procurarmos por `false`, ele encontrará exatamente `false` e não zero. -If we want to check if `item` exists in the array, and don't need the index, then `arr.includes` is preferred. +Se quisermos verificar se `item` existe no array e não precisarmos do índice, então `arr.includes` é a opção preferida. -The method [arr.lastIndexOf](mdn:js/Array/lastIndexOf) is the same as `indexOf`, but looks for from right to left. +O método `arr.lastIndexOf` é semelhante a `indexOf`, mas busca da direita para a esquerda. ```js run -let fruits = ['Apple', 'Orange', 'Apple'] +let fruits = ['Maçã', 'Laranja', 'Maçã'] -alert( fruits.indexOf('Apple') ); // 0 (first Apple) -alert( fruits.lastIndexOf('Apple') ); // 2 (last Apple) +alert( fruits.indexOf('Maçã') ); // 0 (primeira Maçã) +alert( fruits.lastIndexOf('Maçã') ); // 2 (última Maçã) ``` -````smart header="The `includes` method handles `NaN` correctly" -A minor, but noteworthy feature of `includes` is that it correctly handles `NaN`, unlike `indexOf`: +````smart header="O método `includes` lida corretamente com `NaN`." +Uma característica menor, mas notável, do `includes` é que ele lida corretamente com `NaN`, ao contrário do `indexOf`: ```js run const arr = [NaN]; -alert( arr.indexOf(NaN) ); // -1 (wrong, should be 0) -alert( arr.includes(NaN) );// true (correct) +alert( arr.indexOf(NaN) ); // -1 (errado, deveria ser 0) +alert( arr.includes(NaN) );// true (correto) ``` That's because `includes` was added to JavaScript much later and uses the more up to date comparison algorithm internally. ```` -### find and findIndex/findLastIndex +### find e findIndex/findLastIndex -Imagine we have an array of objects. How do we find an object with a specific condition? +Imagine que tenhamos um array de objetos. Como achamos um objeto usando uma condição específica? -Here the [arr.find(fn)](mdn:js/Array/find) method comes in handy. +É nesses momentos que o método [arr.find](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/find) vem a calhar. -The syntax is: +Sua sintaxe é: ```js let result = arr.find(function(item, index, array) { - // if true is returned, item is returned and iteration is stopped - // for falsy scenario returns undefined + // se a condição de find resultar em true, então item é retornado e o laço é parado + // se resultar em falso é retornado o valor undefined }); ``` -The function is called for elements of the array, one after another: +A função é chamada para cada elemento do array, um após o outro: -- `item` is the element. -- `index` is its index. -- `array` is the array itself. +- `item` é o elemento. +- `index` é sua posição. +- `array` é o array onde se encontra o elemento. -If it returns `true`, the search is stopped, the `item` is returned. If nothing is found, `undefined` is returned. +Se a função resultar em `true`, a busca é parada e o `item` é retornado. Se nada for achado, `undefined` é retornado. -For example, we have an array of users, each with the fields `id` and `name`. Let's find the one with `id == 1`: +Por exemplo, nós temos um array de usuários, cada um com os campos `id` e `nome`. Vamos achar o usuário com `id == 1`: ```js run let users = [ @@ -313,15 +313,15 @@ let user = users.find(item => item.id == 1); alert(user.name); // John ``` -In real life, arrays of objects are a common thing, so the `find` method is very useful. +Na vida real, arrays de objetos é uma coisa comum, dessa forma, o método `find` é muito útil. -Note that in the example we provide to `find` the function `item => item.id == 1` with one argument. That's typical, other arguments of this function are rarely used. +Note que no exemplo nós demos para `find` uma função `item => item.id == 1` com somente um argumento. Os outros argumentos dessa função raramente são usados. -The [arr.findIndex](mdn:js/Array/findIndex) method has the same syntax, but returns the index where the element was found instead of the element itself. The value of `-1` is returned if nothing is found. +O método [arr.findIndex](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) é exatamente o mesmo, mas retorna a posição onde o elemento foi encontrado e não seu elemento e `-1` é retornado quando nada é encontrado. -The [arr.findLastIndex](mdn:js/Array/findLastIndex) method is like `findIndex`, but searches from right to left, similar to `lastIndexOf`. +O método [arr.findLastIndex](mdn:js/Array/findLastIndex) é semelhante a `findIndex`, mas pesquisa da direita para a esquerda, similar a `lastIndexOf`. -Here's an example: +Eis um exemplo: ```js run let users = [ @@ -331,29 +331,29 @@ let users = [ {id: 4, name: "John"} ]; -// Find the index of the first John +// Encontra o índice do primeiro John alert(users.findIndex(user => user.name == 'John')); // 0 -// Find the index of the last John +// Encontra o índice do último John alert(users.findLastIndex(user => user.name == 'John')); // 3 ``` ### filter -The `find` method looks for a single (first) element that makes the function return `true`. +O método `find` procura por um único (e o primeiro) elemento que fizer a função retornar `true`. -If there may be many, we can use [arr.filter(fn)](mdn:js/Array/filter). +Se quisermos que retorne mais de um elemento, podemos usar [arr.filter(fn)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/filtro). -The syntax is similar to `find`, but `filter` returns an array of all matching elements: +A sintaxe é semelhante à de `find`, mas `filter` retorna um array com todos os elementos correspondentes: ```js let results = arr.filter(function(item, index, array) { - // if true item is pushed to results and the iteration continues - // returns empty array if nothing found + //se um elemento que atende aos requisitos for alocado na variável resultado e o loop continuar + //retorna um array vazio por completar um cenário falso }); ``` -For instance: +Por exemplo: ```js run let users = [ @@ -362,31 +362,31 @@ let users = [ {id: 3, name: "Mary"} ]; -// returns array of the first two users +//retorna um array com os dois primeiros usuários let someUsers = users.filter(item => item.id < 3); alert(someUsers.length); // 2 ``` -## Transform an array +## Transformando um array -Let's move on to methods that transform and reorder an array. +Esta seção irá abordar os métodos que transformam ou reorganizam um array. ### map -The [arr.map](mdn:js/Array/map) method is one of the most useful and often used. +O método [arr.map](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/map) é um dos mais úteis e usados por programadores. -It calls the function for each element of the array and returns the array of results. +A função é chamada para cada elemento do array e retorna o array de resultados. -The syntax is: +Sua sintaxe é: ```js let result = arr.map(function(item, index, array) { - // returns the new value instead of item -}); + //retorna um novo valor e não seu item +}) ``` -For instance, here we transform each element into its length: +Abaixo, transformamos cada elemento em seu tamanho: ```js run let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length); @@ -395,32 +395,32 @@ alert(lengths); // 5,7,6 ### sort(fn) -The call to [arr.sort()](mdn:js/Array/sort) sorts the array *in place*, changing its element order. +O método [arr.sort](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) ordena um array colocando os elementos *em seus devidos lugares*. -It also returns the sorted array, but the returned value is usually ignored, as `arr` itself is modified. +Também retorna o array ordenado, mas o valor retornado geralmente é ignorado, pois o próprio `arr` é modificado. -For instance: +Exemplo: ```js run let arr = [ 1, 2, 15 ]; -// the method reorders the content of arr +// o método reordena o conteúdo do arr arr.sort(); alert( arr ); // *!*1, 15, 2*/!* ``` -Did you notice anything strange in the outcome? +Você notou alguma coisa estranha non resultado? -The order became `1, 15, 2`. Incorrect. But why? +A ordem ficou `1, 15, 2`. Incorreto. Mas por quê? -**The items are sorted as strings by default.** +**Os itens são ordenados como strings por padrão.** -Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed `"2" > "15"`. +Literalmente, todos os elementos são convertidos para strings e então comparados. A ordenação lexicográfica é aplicada e, de fato, `"2" > "15"`. -To use our own sorting order, we need to supply a function as the argument of `arr.sort()`. +Para usar nossa própria ordenação, precisamos fornecer uma função como argumento de `arr.sort()`. -The function should compare two arbitrary values and return: +A função deve comparar dois valores arbitrários e retornar: ```js function compare(a, b) { @@ -430,7 +430,7 @@ function compare(a, b) { } ``` -For instance, to sort as numbers: +Por exemplo, para ordenar como números: ```js run function compareNumeric(a, b) { @@ -448,13 +448,13 @@ arr.sort(compareNumeric); alert(arr); // *!*1, 2, 15*/!* ``` -Now it works as intended. +Agora funciona como pretendido. -Let's step aside and think about what's happening. The `arr` can be an array of anything, right? It may contain numbers or strings or objects or whatever. We have a set of *some items*. To sort it, we need an *ordering function* that knows how to compare its elements. The default is a string order. +Vamos parar um pouco e pensar sobre o que exatamente está acontecendo. O `arr` pode ser um array de qualquer coisa, correto? Ele pode conter números ou strings ou elementos HTML ou qualquer outra coisa. Nós vamos ter um array de *alguma coisa*. Para ordená-lo, precisamos de uma *função de ordenação* que saiba comparar os elementos. O padrão é uma ordenação de strings. -The `arr.sort(fn)` method implements a generic sorting algorithm. We don't need to care how it internally works (an optimized [quicksort](https://en.wikipedia.org/wiki/Quicksort) or [Timsort](https://en.wikipedia.org/wiki/Timsort) most of the time). It will walk the array, compare its elements using the provided function and reorder them, all we need is to provide the `fn` which does the comparison. +O método `arr.sort(fn)` possui uma implementação interna (built-in) de ordenação de algoritmos. Não precisamos saber exatamente como funciona (na maioria do tempo, ele é [quicksort](https://pt.wikipedia.org/wiki/Quicksort) otimizado). Ele vai percorrer o array, comparar seus elementos usando a função providenciada e reordená-los, tudo que precisamos é fornecer o `fn` que irá fazer a comparação. -By the way, if we ever want to know which elements are compared -- nothing prevents us from alerting them: +A propósito, se em algum momento quisermos saber quais elementos são comparados -- nada nos previne de usar um `alert` neles: ```js run [1, -2, 15, 2, 0, 8].sort(function(a, b) { @@ -463,12 +463,12 @@ By the way, if we ever want to know which elements are compared -- nothing preve }); ``` -The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as possible. +O algoritmo pode até comparar um elemento múltiplas vezes durante o processo, porém ele tenta fazer o menor número de comparações possíveis. -````smart header="A comparison function may return any number" -Actually, a comparison function is only required to return a positive number to say "greater" and a negative number to say "less". +````smart header="Uma função de comparação pode retornar qualquer número" +Na verdade, numa função de comparação é somente exigido que retorne um número positivo para dizer "maior que" e um negativo para "menor que". -That allows to write shorter functions: +Isso permite escrever funções menores: ```js run let arr = [ 1, 2, 15 ]; @@ -479,37 +479,37 @@ alert(arr); // *!*1, 2, 15*/!* ``` ```` -````smart header="Arrow functions for the best" -Remember [arrow functions](info:arrow-functions-basics)? We can use them here for neater sorting: +````smart header="Arrow functions para o melhor" +Você se lembra de [arrow functions](info:function-expressions-arrows#arrow-functions)? Podemos usá-lo aqui para deixar o código mais limpo: ```js arr.sort( (a, b) => a - b ); ``` -This works exactly the same as the longer version above. +Funciona exatamente como a outra versão acima. ```` -````smart header="Use `localeCompare` for strings" -Remember [strings](info:string#correct-comparisons) comparison algorithm? It compares letters by their codes by default. +````smart header="Use `localeCompare` para strings" +Lembra-se do algoritmo de comparação de strings? Por padrão, ele compara letras pelos seus códigos. -For many alphabets, it's better to use `str.localeCompare` method to correctly sort letters, such as `Ö`. +Para muitos alfabetos, é melhor usar o método `str.localeCompare` para ordenar corretamente as letras, como `Ö`. -For example, let's sort a few countries in German: +Por exemplo, vamos ordenar alguns países em alemão: ```js run let countries = ['Österreich', 'Andorra', 'Vietnam']; -alert( countries.sort( (a, b) => a > b ? 1 : -1) ); // Andorra, Vietnam, Österreich (wrong) +alert( countries.sort( (a, b) => a > b ? 1 : -1) ); // Andorra, Vietnam, Österreich (errado) -alert( countries.sort( (a, b) => a.localeCompare(b) ) ); // Andorra,Österreich,Vietnam (correct!) +alert( countries.sort( (a, b) => a.localeCompare(b) ) ); // Andorra,Österreich,Vietnam (correto!) ``` ```` ### reverse -The method [arr.reverse](mdn:js/Array/reverse) reverses the order of elements in `arr`. +O método [arr.reverse](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) reverte a ordem dos elementos em `arr`. -For instance: +Exemplo: ```js run let arr = [1, 2, 3, 4, 5]; @@ -518,15 +518,15 @@ arr.reverse(); alert( arr ); // 5,4,3,2,1 ``` -It also returns the array `arr` after the reversal. +Ele também retornar o array `arr` depois de revertê-lo. -### split and join +### split e join -Here's the situation from real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: `John, Pete, Mary`. But for us an array of names would be much more comfortable than a single string. How to get it? +Aqui vai uma situação que ocorre na vida real. Digamos que estamos escrevendo uma aplicativo de mensagem e uma pessoa coloca uma lista dos recebedores delimitado por virgulas: `John, Pete, Mary`. Mas para nós um array de nomes seria muito mais confortável do que uma única string. Como fazer isso? -The [str.split(delim)](mdn:js/String/split) method does exactly that. It splits the string into an array by the given delimiter `delim`. +O método [str.split(delim)](https://www.devmedia.com.br/javascript-split-dividindo-separando-strings/39254) faz exatamente isso. Ele separa a string em uma array dado por seu delimitador `delim`. -In the example below, we split by a comma followed by a space: +No exemplo abaixo, nós separamos por uma vírgula seguido por um espaço: ```js run let names = 'Bilbo, Gandalf, Nazgul'; @@ -534,11 +534,11 @@ let names = 'Bilbo, Gandalf, Nazgul'; let arr = names.split(', '); for (let name of arr) { - alert( `A message to ${name}.` ); // A message to Bilbo (and other names) + alert( `Uma mensagem para ${name}.` ); // Uma mensagem para Bilbo (outros nomes) } ``` -The `split` method has an optional second numeric argument -- a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used though: +O método `split` possui um segundo argumento numérico opcional -- um limite para o tamanho de uma array. Se for aprovado, então os outros elemento são ignorados. Na prática, é raramente usado: ```js run let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2); @@ -546,19 +546,19 @@ let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2); alert(arr); // Bilbo, Gandalf ``` -````smart header="Split into letters" -The call to `split(s)` with an empty `s` would split the string into an array of letters: +````smart header="Separe por letras" +Ao chamar `split(s)` com o `s` vazio, separaria a string e teríamos um array de letras: ```js run -let str = "test"; +let str = "teste"; -alert( str.split('') ); // t,e,s,t +alert( str.split('') ); // t,e,s,t,e ``` ```` -The call [arr.join(glue)](mdn:js/Array/join) does the reverse to `split`. It creates a string of `arr` items joined by `glue` between them. +O método [arr.join(separator)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/join) faz o contrário de `split`. Ele cria uma string dos itens de `arr` juntando-os por um `separator` entre eles. -For instance: +Por exemplo: ```js run let arr = ['Bilbo', 'Gandalf', 'Nazgul']; @@ -570,13 +570,13 @@ alert( str ); // Bilbo;Gandalf;Nazgul ### reduce/reduceRight -When we need to iterate over an array -- we can use `forEach`, `for` or `for..of`. +Quando precisamos percorrer um array -- podemos usar `forEach`, `for` ou `for..of`. -When we need to iterate and return the data for each element -- we can use `map`. +Quando precisamos percorrer e retornar uma informação por cada elemento -- usamos o `map`. -The methods [arr.reduce](mdn:js/Array/reduce) and [arr.reduceRight](mdn:js/Array/reduceRight) also belong to that breed, but are a little bit more intricate. They are used to calculate a single value based on the array. +Os métodos [arr.reduce](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) e [arr.reduceRight](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight) também pertence á esse grupo, porém eles podem ser um pouco mais confusos. Eles são usados para calcular um único valor baseado em um array. -The syntax is: +Sua sintaxe é: ```js let value = arr.reduce(function(accumulator, item, index, array) { @@ -584,100 +584,99 @@ let value = arr.reduce(function(accumulator, item, index, array) { }, [initial]); ``` -The function is applied to all array elements one after another and "carries on" its result to the next call. +A função é aplicada a todos os elementos do array um após o outro e "repassa" seu resultado para a próxima chamada. -Arguments: +- Arguments: -- `accumulator` -- is the result of the previous function call, equals `initial` the first time (if `initial` is provided). -- `item` -- is the current array item. -- `index` -- is its position. -- `array` -- is the array. +- `accumulator` -- é o resultado da chamada anterior de função, é igual a `initial` na primeira vez (se `initial` for fornecido). +- `item` -- é o atual item da array. +- `index` -- é sua posição. +- `array` -- é a array. -As the function is applied, the result of the previous function call is passed to the next one as the first argument. +À medida que a função é aplicada, o resultado da chamada da função anterior é passado para a próxima como primeiro argumento. -So, the first argument is essentially the accumulator that stores the combined result of all previous executions. And at the end, it becomes the result of `reduce`. +Portanto, o primeiro argumento é essencialmente o acumulador que armazena o resultado combinado de todas as execuções anteriores. E, no final, torna-se o resultado de `reduce`. -Sounds complicated? +Parece complicado? -The easiest way to grasp that is by example. +O jeito mais fácil de se entender é por meio de exemplos. -Here we get a sum of an array in one line: +Aqui vamos somar os elementos de um array: ```js run let arr = [1, 2, 3, 4, 5]; - let result = arr.reduce((sum, current) => sum + current, 0); alert(result); // 15 ``` -The function passed to `reduce` uses only 2 arguments, that's typically enough. +A função passada para `reduce` usa apenas 2 argumentos, o que normalmente é suficiente. -Let's see the details of what's going on. +Vamos entender os detalhes do que está acontecendo. -1. On the first run, `sum` is the `initial` value (the last argument of `reduce`), equals `0`, and `current` is the first array element, equals `1`. So the function result is `1`. -2. On the second run, `sum = 1`, we add the second array element (`2`) to it and return. -3. On the 3rd run, `sum = 3` and we add one more element to it, and so on... +1. Na 1º execução, podemos notar que o último argumento de `reduce` é igual a `0`, logo esse será o valor inicial de `sum`, e `current` terá o valor do primeiro elemento do array: `1`. A função está retornando a soma das variáveis `sum` e `current`, então o resultado é `1`. +2. Na 2º execução, `sum` passa a ter o resultado como valor `sum = 1` e `current` passa a ter o segundo elemento do array `current = 2` e, então, retorna a soma destes. +3. Na 3º execução, `sum = 3` e `current` passa a ter o próximo elemento do array e assim por diante... -The calculation flow: +Abaixo, a imagem mostra o fluxo da calculação: ![](reduce.svg) -Or in the form of a table, where each row represents a function call on the next array element: +Ou por meio de uma tabela, onde cada linha representa uma chamada da função no próximo elemento do array: -| |`sum`|`current`|result| +| |`sum`|`current`|`result`| |---|-----|---------|---------| -|the first call|`0`|`1`|`1`| -|the second call|`1`|`2`|`3`| -|the third call|`3`|`3`|`6`| -|the fourth call|`6`|`4`|`10`| -|the fifth call|`10`|`5`|`15`| +|1º chamada|`0`|`1`|`1`| +|2º chamada|`1`|`2`|`3`| +|3º chamada|`3`|`3`|`6`| +|4º chamada|`6`|`4`|`10`| +|5º chamada|`10`|`5`|`15`| -Here we can clearly see how the result of the previous call becomes the first argument of the next one. +Como podemos ver, o resultado da última chamada se torna o valor do primeiro argumento na próxima chamada. -We also can omit the initial value: +Podemos também omitir o valor inicial: ```js run let arr = [1, 2, 3, 4, 5]; -// removed initial value from reduce (no 0) -let result = arr.reduce((sum, current) => sum + current); +// valor inicial de reduce foi removido (sem 0) +let resultado = arr.reduce((sum, current) => sum + current); alert( result ); // 15 ``` -The result is the same. That's because if there's no initial, then `reduce` takes the first element of the array as the initial value and starts the iteration from the 2nd element. +O resultado é o mesmo. Isto ocorre porque, se não houver um valor inicial, `reduce` irá pegar o primeiro elemento do array como este valor e `current` começará a partir do 2º elemento. -The calculation table is the same as above, minus the first row. +A tabela de calculação será a mesma de cima, menos a primeira linha. -But such use requires an extreme care. If the array is empty, then `reduce` call without initial value gives an error. +Porém, o uso deste método requer extremo cuidado. Se um array estiver vazio e `reduce` for acionado sem um valor inicial, será retornado um erro. -Here's an example: +Aqui esta um exemplo: ```js run let arr = []; -// Error: Reduce of empty array with no initial value -// if the initial value existed, reduce would return it for the empty arr. +// Erro: Reduce de array vazia sem valor inicial +// se o valor inicial existir, reduce irá retorná-lo para dentro da array vazia. arr.reduce((sum, current) => sum + current); ``` -So it's advised to always specify the initial value. +Portanto, é aconselhável que o valor inicial seja sempre colocado. -The method [arr.reduceRight](mdn:js/Array/reduceRight) does the same, but goes from right to left. +O método [arr.reduceRight](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight) faz o mesmo, mas começando da direita para a esquerda. ## Array.isArray -Arrays do not form a separate language type. They are based on objects. +Arrays não formam um outro tipo de linguagem. Eles são baseados em objetos. -So `typeof` does not help to distinguish a plain object from an array: +Mesmo usando `typeof` não é possível distinguir um objeto de um array: ```js run -alert(typeof {}); // object -alert(typeof []); // object (same) +alert(typeof {}); // objeto +alert(typeof []); // objeto (same) ``` -...But arrays are used so often that there's a special method for that: [Array.isArray(value)](mdn:js/Array/isArray). It returns `true` if the `value` is an array, and `false` otherwise. +...Mas arrays são usados tão frequentemente que há um método especial para isso: [Array.isArray(valor)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). Este método retorna `true` se o `valor` for um array e `false` se não for. ```js run alert(Array.isArray({})); // false @@ -685,25 +684,25 @@ alert(Array.isArray({})); // false alert(Array.isArray([])); // true ``` -## Most methods support "thisArg" +## A maioria dos métodos suportam "thisArg" -Almost all array methods that call functions -- like `find`, `filter`, `map`, with a notable exception of `sort`, accept an optional additional parameter `thisArg`. +Quase todos os métodos arrays que chamam uma função -- como `find`, `filter`, `map`, com exceção de `sort` -- aceitam um parâmetro adicional opcional `thisArg`. -That parameter is not explained in the sections above, because it's rarely used. But for completeness, we have to cover it. +Este parâmetro não foi explicado nas seções anteriores porque é raramente usado. Entretanto, para um ensinamento melhor e completo, decidimos mostrá-lo. -Here's the full syntax of these methods: +Abaixo mostramos a sintaxe completa destes métodos: ```js arr.find(func, thisArg); arr.filter(func, thisArg); arr.map(func, thisArg); // ... -// thisArg is the optional last argument +// thisArg é o último argumento opcional ``` -The value of `thisArg` parameter becomes `this` for `func`. +O valor do parâmetro `thisArg` se torna o `this` para `func`. -For example, here we use a method of `army` object as a filter, and `thisArg` passes the context: +Por exemplo, aqui usamos um método do objeto `army` como filtro, e `thisArg` passa o contexto: ```js run let army = { @@ -722,7 +721,7 @@ let users = [ ]; *!* -// find users, for who army.canJoin returns true +// Encontrar usuários para os quais army.canJoin retorna true let soldiers = users.filter(army.canJoin, army); */!* @@ -731,53 +730,53 @@ alert(soldiers[0].age); // 20 alert(soldiers[1].age); // 23 ``` -If in the example above we used `users.filter(army.canJoin)`, then `army.canJoin` would be called as a standalone function, with `this=undefined`, thus leading to an instant error. - -A call to `users.filter(army.canJoin, army)` can be replaced with `users.filter(user => army.canJoin(user))`, that does the same. The latter is used more often, as it's a bit easier to understand for most people. +Se no exemplo acima usássemos `users.filter(army.canJoin)`, então `army.canJoin` seria chamada como uma função independente, com `this=undefined`, o que levaria a um erro imediato. -## Summary +Uma chamada para `users.filter(army.canJoin, army)` pode ser substituída por `users.filter(user => army.canJoin(user))`, que faz o mesmo. Esta última é usada com mais frequência, pois é um pouco mais fácil de entender para a maioria das pessoas. -A cheat sheet of array methods: +## Resumo -- To add/remove elements: - - `push(...items)` -- adds items to the end, - - `pop()` -- extracts an item from the end, - - `shift()` -- extracts an item from the beginning, - - `unshift(...items)` -- adds items to the beginning. - - `splice(pos, deleteCount, ...items)` -- at index `pos` deletes `deleteCount` elements and inserts `items`. - - `slice(start, end)` -- creates a new array, copies elements from index `start` till `end` (not inclusive) into it. - - `concat(...items)` -- returns a new array: copies all members of the current one and adds `items` to it. If any of `items` is an array, then its elements are taken. +Uma *cola* com os métodos arrays abordados: -- To search among elements: - - `indexOf/lastIndexOf(item, pos)` -- look for `item` starting from position `pos`, and return the index or `-1` if not found. - - `includes(value)` -- returns `true` if the array has `value`, otherwise `false`. - - `find/filter(func)` -- filter elements through the function, return first/all values that make it return `true`. - - `findIndex` is like `find`, but returns the index instead of a value. +- Para adicionar/remover elementos: + - `push(...items)` -- adiciona itens no final, + - `pop()` -- retira um item do final, + - `shift()` -- retira um item do começo, + - `unshift(...items)` -- adiciona um item no começo. + - `splice(posicao, quantidade, ...items)` -- no index `posicao`, deleta uma certa `quantidade` de elementos e insere outros `items`. + - `slice(comeco, fim)` -- cria um novo array, copia elementos a partir da posição `comeco` até `fim` (que não é incluso) para dentro do array. + - `concat(...items)` -- retorna um novo array: une elementos de um array atual com outros `items` e adiciona a array nova. Se algum `items` for um array, então seus elementos também são capturados e adicionados. -- To iterate over elements: - - `forEach(func)` -- calls `func` for every element, does not return anything. +- Para procurar entre os elementos: + - `indexOf/lastIndexOf(item, posicao)` -- procura por `item` começando pela `posicao`, retorna o index/posição ou `-1` se não for encontrado. + - `includes(valor)` -- retorna `true` se o array possuir o `valor`, do contrário, retornará `false`. + - `find/filter(func)` -- filtra elementos por meio de uma função, retorna o primeiro - ou todos - valor que fizer a função retornar `true`. + - `findIndex` é como `find`, mas retorna o index e não o valor. + +- Para percorrer os elementos: + - `forEach(func)` -- chama `func` para cada elemento, não retorna um valor. -- To transform the array: - - `map(func)` -- creates a new array from results of calling `func` for every element. - - `sort(func)` -- sorts the array in-place, then returns it. - - `reverse()` -- reverses the array in-place, then returns it. - - `split/join` -- convert a string to array and back. - - `reduce/reduceRight(func, initial)` -- calculate a single value over the array by calling `func` for each element and passing an intermediate result between the calls. +- Para transformar um array: + - `map(func)` -- cria um novo array a partir do resultado da chamada de `func` para cada elemento. + - `sort(func)` -- ordena o array e o retorna. + - `reverse()` -- inverte o array e o retorna. + - `split/join` -- converte uma string para array/array para string. + - `reduce(func, initial)` -- calcula um único valor a partir de um array ao chamar `func` para cada elemento e passando um resultado intermediário entre as chamadas. -- Additionally: - - `Array.isArray(value)` checks `value` for being an array, if so returns `true`, otherwise `false`. +- Adicional: + - `Array.isArray(arr)` checa se `arr` é um array. -Please note that methods `sort`, `reverse` and `splice` modify the array itself. +Por favor, note que os métodos `sort`, `reverse` e `splice` modificam o array. -These methods are the most used ones, they cover 99% of use cases. But there are few others: +Este métodos são os mais usados, eles cobrem 99% em casos de uso. Porém, existem outros: -- [arr.some(fn)](mdn:js/Array/some)/[arr.every(fn)](mdn:js/Array/every) check the array. +- [arr.some(fn)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/some)/[arr.every(fn)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/every) examina o array. - The function `fn` is called on each element of the array similar to `map`. If any/all results are `true`, returns `true`, otherwise `false`. + A função `fn` é chamada em cada elemento do array como em `map`. Se algum/todos os resultados for `true`, retorna `true`, do contrário `false`. - These methods behave sort of like `||` and `&&` operators: if `fn` returns a truthy value, `arr.some()` immediately returns `true` and stops iterating over the rest of items; if `fn` returns a falsy value, `arr.every()` immediately returns `false` and stops iterating over the rest of items as well. + Esses métodos se comportam de forma semelhante aos operadores `||` e `&&`: se `fn` retornar um valor verdadeiro (true), `arr.some()` retornará imediatamente `true` e interromperá a iteração sobre os demais itens; se `fn` retornar um valor falso (false), `arr.every()` retornará imediatamente `false` e ​​também interromperá a iteração sobre os demais itens. - We can use `every` to compare arrays: + Podemos usar `every` para comparar arrays: ```js run function arraysEqual(arr1, arr2) { @@ -787,16 +786,16 @@ These methods are the most used ones, they cover 99% of use cases. But there are alert( arraysEqual([1, 2], [1, 2])); // true ``` -- [arr.fill(value, start, end)](mdn:js/Array/fill) -- fills the array with repeating `value` from index `start` to `end`. +- [arr.fill(valor, comeco, fim)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) -- preenche um array com o `valor` dado repetitivamente a partir da posição `comeco` até `fim`. -- [arr.copyWithin(target, start, end)](mdn:js/Array/copyWithin) -- copies its elements from position `start` till position `end` into *itself*, at position `target` (overwrites existing). +- [arr.copyWithin(target, start, end)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) -- copia *seus próprios elementos* e os leva para outra posição *dentro da mesma array*. A cópia dos elementos começa a partir da posição `start` até a posição `end`, e os elementos são realocados para a posição `target` (sobescrevendo os elementos existentes). Este método não adiciona novos itens ao array. -- [arr.flat(depth)](mdn:js/Array/flat)/[arr.flatMap(fn)](mdn:js/Array/flatMap) create a new flat array from a multidimensional array. +- [arr.flat(depth)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)/[arr.flatMap(fn)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) cria um novo array plano a partir de um array multidimensional.. -For the full list, see the [manual](mdn:js/Array). +Para a lista completa, veja o [manual](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array). -At first sight, it may seem that there are so many methods, quite difficult to remember. But actually, that's much easier. +Á primeira vista, pode parecer que são muitos métodos e que se torna difícil de lembrá-los. Mas, na verdade, isso é mais simples do que parece. -Look through the cheat sheet just to be aware of them. Then solve the tasks of this chapter to practice, so that you have experience with array methods. +Examine esta lista de *cola* só para ter uma noção deles e depois resolva os exercícios deste capítulo para praticar. Desta forma, você vai ter uma experiência com métodos arrays. -Afterwards whenever you need to do something with an array, and you don't know how -- come here, look at the cheat sheet and find the right method. Examples will help you to write it correctly. Soon you'll automatically remember the methods, without specific efforts from your side. +Mais tarde, sempre que precisar fazer algo com arrays -- e você não souber como -- venha até aqui, olhe nossa cola e ache o método correto. Exemplos vão lhe ajudar a escrever corretamente. Logo você irá lembrar dos métodos automaticamente, sem esforços específicos.